2

There is a directory containing several files and i want to grep for files containing a string "str1" say. for this, the following cmd works perfectly fine :

 grep "str1" -r * 

Now, i want to grep for files which contain two strings say str1 and str2. can anyone please let me know how to do that.

2
  • Agree with what Theolodis said: "you could have googled yourself ;)" Commented Sep 18, 2013 at 7:15
  • this approach which theolodis told didnt work for me. i had already googled and when i couldn't get the answer,i asked on this forum Commented Sep 18, 2013 at 7:26

4 Answers 4

3

grep "str1" -r -l * Will print just the list of file names of the files with matches so

grep str2 `grep "str1" -r -l *` 

Should do the job by supplying that lists as the file names input to grep.

Thanks to this answer for the refresher on how to do it.

Sign up to request clarification or add additional context in comments.

Comments

2

The following should work for you:

find . -type f -exec sh -c "grep -q str1 {} && grep -q str2 {} && echo {}" \; 

This would return all files in the current directory (and subdirectories) that contain both str1 and str2.

Comments

1

Another approach is to join the sorted result of two calls to "grep -l"

join <(grep -l "str1" * | sort) <(grep -l "str2" * | sort) 

Comments

0
grep "str1" -r * | grep "str2" 

this will solve your problem... you could have googled yourself ;)

5 Comments

I had already tried the above approach, this doesn't work. The output for search of single string say "str1" comes like : Binary file ./webcrome1.pcap matches Binary file ./webcrome2.pcap matches Binary file ./webcrome3.pcap matches
@Theolodis LMGTFY links are considered a little rude on SO, and your question gets the point across without it.
@Chilledrat removed it
This only works if both str1 and str2 are on the same line. I don't think that's what is asked for.
Unfortunately this will only match lines that contain both "str12" and "str2" as the input for the second grep will be the matching lines from the first.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.