Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:


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

share|improve this question
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
up vote 7 down vote accepted

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*
share|improve this answer
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

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

share|improve this answer
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 posting your answer, you agree to the privacy policy and terms of service.

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