Grep only subdirectories matching pattern

grep

I have a directory tree consisting of several thousand subdirectories, but I frequently need to grep only a small subset of those directories. How can I grep only those subdirectories matching a pattern?

For example, suppose I have these subdirectories which I want to grep in:

...
...
...
/foo
/fooLib
/fooHandler
/fooGizmo
...
...
...

The ... entries above represent the thousands of other directories I don't want to grep in.

Supposing I'm looking for all instances of bar, if I do this:

grep -n --recursive bar *

I would find what I'm looking for, but in all of the directories. How can I search in only those subdirectories matching the pattern foo*?

Best Answer

You can use grep and find combination as below :

find /{foo,fooLib,fooHandler,fooGizmo} -type f -exec grep -l "test" {} \;

Or you can use

find /foo* -type f -exec grep -l "test" {} \;

Or using grep only

grep -R "test" /foo*
Related Question