How to run grep with multiple AND patterns?
I would like to get the multi pattern match with implicit AND between patterns, i.e. equivalent to running several greps in a sequence:
grep pattern1 | grep pattern2 | ...
So how to convert it to something like?
grep pattern1 & pattern2 & pattern3
I would like to use single grep because I am building arguments dynamically, so everything has to fit in one string. Using filter is system feature, not grep, so it is not an argument for it.
Don't confuse this question with:
This is an OR multi pattern match.
Similar question on SO: Check if multiple strings or regexes exist in a file
agrepcan do it with this syntax:
grep, when built with PCRE support, you can do:
grep -P '^(?=.*pattern1)(?=.*pattern2)'
grep -X '.*pattern1.*&.*pattern2.*'
<x>&<y>matches strings that match both
a&bwould never match as there's no such string that can be both
bat the same time).
If the patterns don't overlap, you may also be able to do:
grep -e 'pattern1.*pattern2' -e 'pattern2.*pattern1'
The best portable way is probably with
awkas already mentioned:
awk '/pattern1/ && /pattern2/'
sed -e '/pattern1/!d' -e '/pattern2/!d'
Please beware that all those will have different regular expression syntax.
@Raman 2.04 from 1992 already had it. I've no reason to believe it wasn't there from the start. Newer (after 1992) versions of `agrep` can be found included with glimpse/webglimpse. Possibly you have a different implementation. I had a mistake for the ast-grep version though, the option for _augmented regexps_ is `-X`, not `-A`.
@StéphaneChazelas Thanks, I have `agrep` 0.8.0 on Fedora 23. This appears to be a different `agrep` than the one you reference.
@StéphaneChazelas Indeed it is. Too bad Fedora doesn't have the `agrep` you are referring to, out of the box.
@Techiee, you mean the count of lines that match either pattern or the count of occurrences of each pattern? In any case, it seems it would be a different question.
@StéphaneChazelas, Right now `awk '/pattern1/ && /pattern2/'` is printing all the lines, i want the print the count of such lines. Can you help? Thanks
@StéphaneChazelas: I got it, `awk '/pattern1/ && /pattern2/' filename | wc -l` will give me desired output.