14

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

1
  • 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? Jan 15, 2013 at 23:25

2 Answers 2

15

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*
8
  • Can I do this without specifying the subdirectories explicityly? Rather, by using a wildcard such as foo*? Jan 15, 2013 at 15:48
  • @JohnDibling yes i have updated exactly what you are saying :) Jan 15, 2013 at 15:50
  • The latter suggestion (grep -R "test" /foo*) is exactly what I'm actually doing now, so I'll accept. Jan 15, 2013 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? Oct 19, 2018 at 15:57
  • This provides the lines matching the grep, but the location of the data (the file it's in) is lost. Is there any way to retain that?
    – Jontia
    Nov 1, 2019 at 14:32
0

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

1
  • 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*/*? Jan 15, 2013 at 15:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .