7

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*?

  • Do you want to search only in /foo and friends? In /foo and /foo/bar and /foo/bar/qux and so on but not /wibble/foo? In /foo and /wibble/foo but not /foo/bar? In /foo and /foo/bar and /wibble/foo but not /elsewhere? – Gilles Jan 15 '13 at 23:25
10

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*
  • Can I do this without specifying the subdirectories explicityly? Rather, by using a wildcard such as foo*? – John Dibling Jan 15 '13 at 15:48
  • @JohnDibling yes i have updated exactly what you are saying :) – Rahul Patil Jan 15 '13 at 15:50
  • The latter suggestion (grep -R "test" /foo*) is exactly what I'm actually doing now, so I'll accept. – John Dibling Jan 15 '13 at 15:54
  • Thank you for this. I'm using the first pattern, but would love to understand a few things about it - for example, what do the ending {} and backslash do? – cale_b Oct 19 '18 at 15:57
0

try grep foo* <other parts> eg: grep foo* -name "book*"

  • If I'm looking for all instance of bar in all files in subdirectories named foo*, should this be like this: grep --recursive bar ./foo*/*? – John Dibling Jan 15 '13 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.