You can do this with a short script:
for FILE in *
do
grep -q foo $FILE && grep -q 321 $FILE && echo $FILE
done
You can also do this on one line:
for FILE in *; do grep -q foo $FILE && grep -q 321 $FILE && echo $FILE; done
grep
returns 0 (true) if it found the string and the &&
separating the commands means that the second one will only run if the first one was true. The -q
option makes sure that grep
does not output anything.
The echo will only run if both strings were found in the same file.
I thought of a different way to do it. This way will probably be more efficient if the files in question are larger than your installed RAM as it only has to grep
through each file once.
for FILE in *
do
test $(egrep -o "foo|321" $FILE | uniq | sort | uniq | wc -l) -eq 2 && echo $FILE
done
and the one-line version:
for FILE in *; do test $(egrep -o "foo|321" $FILE | uniq | sort | uniq | wc -l) -eq 2 && echo $FILE; done
321
instead ofbar
:-D – Stack Underflow Feb 22 '19 at 22:14