1

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 {}"

3 Answers 3

3
awk '/ItemA/{f1=1} /ItemB/{f2=1} END{ exit (f1 && f2 ? 0 : 1) }' file
Sign up to request clarification or add additional context in comments.

Comments

3
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.

1 Comment

+1 for concision. OSX users: Use --null instead of -Z with grep.
1

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 {}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.