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. Commented Feb 3, 2015 at 14:28

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.