Bash – executing multiple greps in a single find command

bashfindgrep

I want to use find command to find some files containing multiple patterns at the same time.

I tried something like this:

find . -name "*.xml" -exec grep -iH keyword1 + && grep -iH "keyword2" {} \;

But the above command doesn't work.

Is it possible to do it in bash?

Best Answer

As I understand, you want to list files that contain both "keyword1" and "keyword2". To do that, you can use two -exec tests in following way:

find . -name "*.xml" -exec grep -iq keyword1 {} \; -exec grep -iH keyword2 {} \;

This will run the second grep conditionally - if the first one returned true. The -q option prevents output from the first grep, as it would list all the files that include only "keyword1".

Since the -H option outputs the matching line together with the file name, you'd probably want to use -l instead. So

find . -name "*.xml" -exec grep -iq keyword1 {} \; -exec grep -il keyword2 {} \;

This will yield similar output to what Caleb suggested, but without the need of additional -print.

Related Question