Find all files containing a `string`

Find all files containing a `string` - the Grep way!


1 min read
Find all files containing a `string`

Adding to my TIL series.

I working on building an set of addon(s) for a rather large and complex opensource project. While trying to tweak some confugration, I wanted to be able to find all the files - where the configuration values were being picked up from. Being my lazy self today, and not in the mood to read through all the documentation –  I'm going to use grep to help me find all the config files.

grep -rnw '/path/to/the/project/root/' -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/the/project/root/' -e "pattern"

This will exclude searching all the files ending with .o extension:

grep --exclude=*.o -rnw '/path/to/the/project/root/' -e "pattern"

For directories it's possible to exclude one or more directories using the --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/the/project/root/' -e "pattern"

This worked very well for what I was looking for.

Related Articles

GO TOP