1

I'm trying to run multiple AND combination in grep command, I was able to run using two patterns:

grep -E 'pattern1.*pattern2' filename

Is it possible to use three or four patterns using the above method?

Erathiel
  • 1,575
Tom
  • 68

2 Answers2

7

If the order of the patterns is fixed then you can easily use grep as in:

grep -E 'pattern1.*pattern2.*pattern3'

But in case that all patterns must be present and they may appear in any order then you get combinatorical complexity; e.g. for two patterns:

grep -E '(pattern1.*pattern2|pattern2.*pattern1)'

(and for three patterns you'd have already eight combinations).

In such cases (i.e. when using grep) it's better to cascade the calls in a pipeline of one grep instance per pattern:

grep pattern1 <infile | grep pattern2 | grep pattern3

Each instance will filter only the lines that match their pattern, and the overall result will contain only lines that have all the patterns.

A better approach that leads to the clearest solution is to use awk:

awk '/pattern1/ && /pattern2/ && /pattern3/'

where the ordering would not matter in such an expression.

Janis
  • 14,222
0

Yes. You can construct any regular expression you want and use it as the pattern in a grep command. It simply has to be a legal regular expression.

John
  • 17,011