Tags

, , , , , , , , , ,

For grepping line-by-line in a file filename, I often find these very useful

Match pattern1 OR pattern2 in the same line:
$ grep -E 'pattern1|pattern2' filename

Match pattern1 AND pattern2 in the same line:
$ grep -E 'pattern1.*pattern2' filename
The above command searches for pattern1 followed by pattern2. If the order does not matter or you want to search them in either order, then use the follwoing
$ grep -E 'pattern1.*pattern2|pattern2.*pattern1' filename
The pipe enables the OR search which we saw earlier. Another option for this situation (i.e., AND search when the order is not important):
$ grep -E 'pattern1' filename | grep -E 'pattern2'
which basically greps the STDOUT of the first grep.

Match pattern1 AND pattern2, but NOT pattern3 in the same line:
$ grep -E 'pattern1.*pattern2' filename | grep -Ev 'pattern3'
when the order of the first two patterns is important. When that order is NOT important:
$ grep -E 'pattern1' filename | grep -E 'pattern2' | grep -Ev 'pattern3'

Match pattern1 OR pattern2, but NOT pattern3 in the same line:
$ grep -E 'pattern1|pattern2' filename | grep -Ev 'pattern3'

N.B. (1) grep -E may be replaced by egrep.ย  I used grep -E everywhere in this post assuming a general case of regular expressions as patterns. Lowercase -e is also used for regex, but this is more “basic” than -E which supports “extended” regex, e.g. regular expression metacharacters like +, ?, | and (). (2) The -v flag is for non-matching grep.