dashwood.net -

Ryan Stefan's Micro Blog

Search Inside Files - The Power of Grep

Nov 112018

I noticed that my blog has footprints that show which script I used which might cause someone to seek it out and try and exploit it. So I was digging through my code looking for an error message so I could change it and was getting very frustrated. So I looked into finding strings inside files and it worked instantly:

# Recursive Find
grep -rnw '<file path>' -e '<string to find>' # Recursive Replace: grep -lR "<search_phrase>" <file path> | xargs sed -i 's/<search_phrase>/<replace_phrase>/g'

# Current Dir
grep -lR "<search_phrase>" . | xargs sed -i 's/<search_phrase>/<replace_phrase>/g'

Original Post Text

grep -rnw '/path/to/somewhere/' -e 'pattern'

  • -r or -R is recursive,
  • -n is line number, and
  • -w stands for match the whole word.
  • -l (lower-case L) can be added to just give the file name of matching files.

Along with these, --exclude, --include, --exclude-dir flags could be used for efficient searching:

This will only search through those files which have .c or .h extensions:

grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
This will exclude searching all the files ending with .o extension:

grep --exclude=*.o -rnw '/path/to/somewhere/' -e "pattern"
For directories it's possible to exclude a particular directory(ies) through --exclude-dir parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:

grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"
This works very well for me, to achieve almost the same purpose like yours.

For more options check man grep.