4

I need to grep some files to see which ones contain a certain word:

grep -l word *

Next I need to grep that list of files to see which ones contain a different word. The easy way would probably be to write a script but I don't know quite how to work it.

  • Which grep? GNU grep? Are you on Linux, Solaris, the BSDs? – muru Nov 22 '15 at 23:26
  • I'm using Linux. – Tim Nov 23 '15 at 2:19
4
grep -l word * | xargs grep word2

Xargs will run the second grep over each file from the first grep.

Regards.

-1
grep -l word1 $(grep -l word2 *)

or maybe for one of the two words on the same line:

grep -w 'word1\|word2' *

see here

-1

If you need to find files containing a word and then filter out those files containing another word, you could use a sequence of commands like this:

grep word * | awk -F ':' '{print $1}'|uniq | xargs grep word2
  • grep word * - will show all files containing "word", the filename will be first in the list.
  • awk -F ':' '{print $1}' - will print only the filename of your results
  • uniq - will make sure that you do not print the filename more than once.
  • xargs grep word2 - will again search in the list of files you got.
  • @don_crissti But combining pieces grep -l word1 * | xargs -d'\n' grep -l word2 works for anything except newline, which is weird enough almost nobody uses it. – dave_thompson_085 Nov 23 '15 at 3:00

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.