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.

devnull
  • 118,548
  • 33
  • 236
  • 227
mezda
  • 3,537
  • 6
  • 30
  • 37
  • Agree with what [Theolodis](http://stackoverflow.com/users/1907026/theolodis) said: "you could have googled yourself ;)" – devnull Sep 18 '13 at 07: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 – mezda Sep 18 '13 at 07:26

4 Answers4

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.

Community
  • 1
  • 1
Steve Barnes
  • 27,618
  • 6
  • 63
  • 73
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.

devnull
  • 118,548
  • 33
  • 236
  • 227
1

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

join <(grep -l "str1" * | sort) <(grep -l "str2" * | sort)
Panos Rontogiannis
  • 4,154
  • 1
  • 24
  • 29
0
grep "str1" -r * | grep "str2"

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

Theolodis
  • 4,977
  • 3
  • 34
  • 53
  • 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 – mezda Sep 18 '13 at 07:22
  • 1
    @Theolodis LMGTFY links are considered [a little rude](http://meta.stackexchange.com/questions/15650/ban-lmgtfy-let-me-google-that-for-you-links/15660#15660) on SO, and your question gets the point across without it. – Chilledrat Sep 18 '13 at 07:44
  • 1
    @Chilledrat removed it – Theolodis Sep 18 '13 at 07:46
  • 1
    This only works if both `str1` and `str2` are on the *same line*. I don't think that's what is asked for. –  Sep 18 '13 at 07:48
  • 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. – Steve Barnes Sep 18 '13 at 07:52