tags:

views:

54

answers:

4

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?

A: 

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.

crazyscot
+4  A: 

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
Kaleb Pederson
+1  A: 
awk '/a/{f=1}/b/{g=1}END{if(f && g) print "matches"}' file
ghostdog74
A: 

See if this works for you:

grep -lP '(?m)(a.*(.*\n)*.*b)|(b.*(.*\n)*.*a)' *
Dennis Williamson