Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep for multiple patterns over multiple files

Tags:

grep

I've been googling around, and I can't find the answer I'm looking for.

Say I have a file, text1.txt, in directory mydir whose contents are:

one
two

and another called text2.txt, also in mydir, whose contents are:

two
three
four

I'm trying to get a list of files (for a given directory) which contain all (not any) patterns I search for. In the example I provided, I'm looking for output somewhere along the lines of:

./text1.txt

or

./text1.txt:one
./text1.txt:two

The only things I've been able to find are concerning matching any patterns in a file, or matching multiple patterns in a single file (which I tried extending to a whole directory, but received grep usage errors).

Any help is much appreciated.

Edit-Things I've tried

grep "pattern1" < ./* | grep "pattern2" ./*

"ambiguous redirect"

grep 'pattern1'|'pattern2' ./*

returns files that match either pattern

like image 540
prelic Avatar asked Sep 14 '11 20:09

prelic


People also ask

Can grep command be used for searching a pattern in more than one file?

grep command can be used for searching a pattern in more than one file.

How can I grep for multiple patterns and print them on the same line?

Use sed to copy the parts of the line that match the pattern to the output, using capture groups. This assumes that the patterns are always in this order on the lines.


1 Answers

One way could be like this:

find . | xargs grep 'pattern1' -sl | xargs grep 'pattern2' -sl
like image 99
brain Avatar answered Nov 03 '22 01:11

brain