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?
views:
54answers:
4
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
2010-09-22 21:00:22
+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
2010-09-22 21:03:42
A:
See if this works for you:
grep -lP '(?m)(a.*(.*\n)*.*b)|(b.*(.*\n)*.*a)' *
Dennis Williamson
2010-09-23 02:47:18