Confused with grep for multiple words

Hi guys and gals,

I have many files that contains many lines of data. I am trying to find a needle in a haystack in that I'm looking only for files that contain word1 AND word2.

I'm using ...

...

but this is finding files that contains word1 OR word2. No good for me. How can I grep to find both words in a single file?

Thanks in advance.

 awk '{if(f!=FILENAME){f=FILENAME;d=1}}/word1/&&d{p=1}/word2/&&d{q=1}p&&q&&d{print f;d=p=q=0}' input_files

So, this will print the file names once if word1 and word2 is found in any order.

--ahamed

Here is an alternate way:

grep -l word1 files.* > file_list
grep -l word2 files.* >> file_list
sort file_list | uniq -c | grep " 2 "

Nice one. :smiley: That's a little more complicated than I was expecting. Will give it a go.

Thanks.

---------- Post updated at 09:34 PM ---------- Previous update was at 09:33 PM ----------

What does the " 2 " do in this?

file_list will have file names which contain both word1 and word2 . i.e. if the file has both word1 and word2, then that file name will be present 2 times in the file_list.
uniq will give the count. So if the count is 2 or more, then it means both the words are present.

--ahamed

Gotcha. Thanks.

grep -w word1 files* > out1

-w option for searching the word

Hi.

See also solutions including demonstration of glark in grep command with AND condition

Best wishes ... cheers, dr