grep for a word, but also mention another word(s) that should appear in the file

1

I'm looking for occurrences of the word 'image' in a folder with many files and subfolders.

The regular grep commands (grep and 'git grep') return over a thousand matches. How can I add something to the grep command, to tell it,

"Find me files that contain the the 'word', but only if the words 'reporter' or 'publisher' is mentioned in that same file

american-ninja-warrior

Posted 2017-09-06T14:40:19.323

Reputation: 211

Answers

1

The following should work:

grep word `grep -E -l 'reporter|publisher'`

The grep command in backquotes will generate a list of files that contain either 'reporter' or 'publisher' (-l tells grep to list files that match instead of giving the usual output, -E is needed to ensure the alternation | works), which are then listed as arguments to the outer grep command, which in turn searches for 'word' (you can add -l to that too if you just want a list of files that match). Note that this is not quite as efficient as writing things out as a single regular expression (it searches more times than absolutely nessecary), but it is generally more easily explained than putting it as a single regex.

Austin Hemmelgarn

Posted 2017-09-06T14:40:19.323

Reputation: 4 345

I like this answer – american-ninja-warrior – 2017-09-06T15:02:43.693

0

First, build a list of files that have reporter|publisher and then use that list as the source for which files you want to search for word.

If you're using ack, you can do this:

ack -l 'reporter|publisher' | ack -x word

where the -x tells the second ack invocation to use the list of files on stdin as the list of files to search.

Andy Lester

Posted 2017-09-06T14:40:19.323

Reputation: 1 121