0

I use grep -r all the time to find occurrences of a string within files in a given directory:

$ grep -r "string" app/assets/javascripts
> app/assets/javascripts/my_file.js: this line contains my string

But what if I want to recursively search through more than one subdirectory of my current directory? The only way I can think of is to run grep twice:

$ grep -r "string" app/assets/javascripts
> app/assets/javascripts/my_file.js: this line contains "string"
$ grep -r "string" spec/javascripts
> app/assets/javascripts/my_file.js: "string" appears here, too.

How can I combine the above two grep commans into a single line? I don't want to search through every single file in ., and --exclude-dir isn't practical because there are too many other directories under . for me to explicitly exclude them all.

Is this possible?

1

1 Answer 1

2

You can specifiy multiple directories in grep:

grep -r "string" app/assets/javascripts spec/javascripts

Alternatively - sometimes more useful is list files to grep by find, and then grep them, for example

find app/assets/javascripts spec/javascripts -type f -print0 |
  xargs -0 grep "string"

or

find app/assets/javascripts spec/javascripts -type f -exec grep -H "string" {} +
1
  • 1
    Yikes, that was easy! I can't believe I never thought to try that. Thanks.
    – GMA
    Commented Feb 3, 2015 at 14:28

You must log in to answer this question.

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