当前位置: 动力学知识库 > 问答 > 编程问答 >

unix - using grep or awk to find files that contain both "a" and "b" that are on different lines

问题描述:

Is there a way to use grep or awk to find text files that contain both e.g. "a" and "b" but in this case "a" and "b" are on different lines?

网友答案:

Here's a simple awk solution:

awk 'BEGIN {acnt=0; bcnt=0;} /a/ {acnt++;} /b/ {bcnt++} END { if (acnt > 0 && bcnt > 0) print "Matches"; }' $FILE

A slightly simpler way is to just use grep, leveraging its return value as an indicator that the value was found:

grep -l a $FILE && grep -l b $FILE && echo "Both a and b found in $FILE"

You may want to redirect standard output, but the above should be simple and functional. You could wrap it in a loop if wanted:

files=""
for x in *; do
    grep -l a $x && grep -l b $x && files="$files $x" # assuming no spaces
done
# now you can iterate over $files
网友答案:
awk '/a/{f=1}/b/{g=1}END{if(f && g) print "matches"}' file
网友答案:

You might be able to cobble something together with some nasty shell which parsed the output of grepping for "a" and used that to build up a list of files to grep for "b", but if it were me I'd put together a short perl script.

网友答案:

See if this works for you:

grep -lP '(?m)(a.*(.*\n)*.*b)|(b.*(.*\n)*.*a)' *
分享给朋友:
您可能感兴趣的文章:
随机阅读: