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


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.

| improve this answer | |

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.

| improve this answer | |

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.