mezda
mezda

Reputation: 3637

how to search for files in a directory containing mulitple strings in linux

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.

Upvotes: 2

Views: 167

Answers (4)

Panos Rontogiannis
Panos Rontogiannis

Reputation: 4172

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

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

Upvotes: 1

Theolodis
Theolodis

Reputation: 5102

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

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

Upvotes: 0

devnull
devnull

Reputation: 123448

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.

Upvotes: 2

Steve Barnes
Steve Barnes

Reputation: 28370

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.

Upvotes: 3

Related Questions