I would like to list the files (using grep -r) that have both of the two keywords (not necessarily on the same line): word1, word2.

When I do the following, I get the files that have word1 or word2:

grep -r 'word1\|word2' .

I also tried the following:

grep -r 'word1|word2'

which does not return anything, but I'm not sure if it's because there are no files that have both these keywords, or there are no files that have both these keywords on the same line.

How can I get the list of files that contain the two keywords somewhere in the file?


One way is to create a list of files containing one keyword, then search this list for the second, as in:

grep -l word2 $(grep -rl word1 .)

If you want to show the matches, add a third grep, as in:

grep -E 'word1|word2' `grep -l word2 $(grep -rl word1 .)`

It is also possible to use sed to perform grep functions, and it may be possible to do what you want in a single scan with sed, but I haven't thought that through.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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