Reputation: 14907
Is there an easy way to search a file for multiple patterns and return success only if both patterns are found.
For example if I had a file:
itemA
itemB
itemC
itemD
I want to print the name of all txt files that have both "itemA" and "itemD"
something like:
find . -name "*.txt" | xargs -n 1 -I {} sh -c "grep 'itemA AND itemB' && echo {}"
Upvotes: 1
Views: 86
Reputation: 123458
Translating your pseudo-code into real:
find . -name "*.txt" | xargs -n 1 -I {} sh -c "grep -q itemA {} && grep -q itemD {} && echo {}"
You could shorten this somewhat by making the second grep
print the filename:
find . -name "*.txt" | xargs -n 1 -I {} sh -c "grep -q itemA {} && grep -l itemD {}"
Upvotes: 1
Reputation: 203254
awk '/ItemA/{f1=1} /ItemB/{f2=1} END{ exit (f1 && f2 ? 0 : 1) }' file
Upvotes: 3
Reputation: 361585
find . -name "*.txt" -exec grep -l 'itemA' {} + | xargs grep -l 'itemB'
Add -Z
to grep and -0
to xargs if you want to be extra careful with special characters.
Upvotes: 3