Grep – Find Multiple AND Patterns in Any Order

grep

Is there any way to use grep to search for entry matching multiple patterns in any order using single condidion?

As showed in How to run grep with multiple AND patterns? for multiple patterns i can use

grep -e 'foo.*bar' -e 'bar.*foo'

but i have to write 2 conditions here, 6 conditions for 3 patterns and so on…
I want to write single condition if possible.
For finding patterns in any order you can suggest to use:

grep -e 'foo' | grep -e 'bar' # at least i do not retype patterns here

and this will work but i would like to see colored output and in this case only bar will be highlighted.

I would like to write condition as easy as

awk '/foo/ && /bar/'

if it is possible for grep (awk does not highlight results and i doubt it can be done easily).

agrep can probably do what i want, but i wonder if my default grep (2.10-1) on ubuntu 12.04 can do this.

Best Answer

If your version of grep supports PCRE (GNU grep does this with the -P or --perl-regexp option), you can use lookaheads to match multiple words in any order:

grep -P '(?=.*?word1)(?=.*?word2)(?=.*?word3)^.*$'

This won't highlight the words, though. Lookaheads are zero-length assertions, they're not part of the matching sequence.

I think your piping solution should work for that. By default, grep only colors the output when it's going to a terminal, so only the last command in the pipeline does highlighting, but you can override this with --color=always.

grep --color=always foo | grep --color=always bar
Related Question