开发者

Grep for multiple patterns over multiple files

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-Thi开发者_运维问答ngs I've tried

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

"ambiguous redirect"

grep 'pattern1'|'pattern2' ./*

returns files that match either pattern


One way could be like this:

find . | xargs grep 'pattern1' -sl | xargs grep 'pattern2' -sl


I think this is what you need (you can add easily more patterns)

grep -EH 'pattern1|pattern2' mydir


To refine brain's answer:

find . -type f -print0 | xargs -0 grep 'pattern1' -slZ | xargs -0 grep 'pattern2' -sl

This will keep grep from trying to search directories, and can properly handle filenames with spaces, if you pass the -Z flag to grep for all but the last pattern and pass -0 to xargs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜