Find file and Find text in files on Linux

Find file by name

Find file by file name or extension

cd /where-to-find/

find . -type -f -name "filename*"

# Find its sub-directories also

find ./ -type -f -name "filename*"

find ./ -type -f -name "*.txt"

Find TEXT in files

Search text "java"
- Recursive (-r)
- Print the filename (-H)
- Ignore case (-i)

cd /where-to-find/
grep -H -r "java" .

# use find
find . -type f | xargs grep java
# or
find . -type f -print0 | xargs -0 grep java

Only search text "java" in .txt files

cd /where-to-find/
grep -irH 'java' *.txt

# or use find
find . -type f -name "*.txt*" | xargs grep java

Find TEXT in files and then replace

OLD_TEXT="wrong"
NEW_TEXT="right"
cd /my/dir
find . -type f -name "*.txt*" | xargs sed "s#$OLD_TEXT#$NEW_TEXT#g"

Loading