This is an old revision of the document!
The grep, egrep, sed and awk are the most common Linux command line tools for parsing files.
From the following article you’ll learn how to match multiple patterns with the OR, AND, NOT operators, using grep, egrep, sed and awk commands from the Linux command line.
I’ll show the examples of how to find the lines, that match any of multiple patterns, how to print the lines of a file, that match each of provided patterns and how to find and print the lines, that do not match a pattern (negative matching).
Find all the lines of a file, that match any of provided patterns.
Using grep and egrep commands:
$ grep "PATTERN1\|PATTERN2" FILE $ grep -E "PATTERN1|PATTERN2" FILE $ grep -e PATTERN1 -e PATTERN2 FILE $ egrep "PATTERN1|PATTERN2" FILE
Using awk command:
$ awk '/PATTERN1|PATTERN2/' FILE
Using sed command:
\\ $ sed -e '/PATTERN1/b' -e '/PATTERN2/b' -e d FILE
It is also often required to grep a file for multiple patterns – when it is needed to find all the lines in a file, that contain not one, but several patterns.
Note, that you can both find the lines in a file that match multiple patterns in the exact order or in the any order.
Use one of the following commands to find and print all the lines of a file, that match multiple patterns.
Using grep command (exact order):
$ grep -E 'PATTERN1.*PATTERN2' FILE
Using grep command (any order):
$ grep -E 'PATTERN1.*PATTERN2|PATTERN2.*PATTERN1' FILE $ grep 'PATTERN1' FILE | grep 'PATTERN2'
$ awk '/PATTERN1.*PATTERN2/' FILE
$ awk '/PATTERN1/ && /PATTERN2/' FILE
$ sed '/PATTERN1.*PATTERN2/!d' FILE
$ sed '/PATTERN1/!d; /PATTERN2/!d' FILE
Find and print all the lines, that do not match a pattern.
Using grep command:
$ grep -v 'PATTERN1' FILE
Using awk command:
$ awk '!/PATTERN1/' FILE
Using sed command:
$ sed -n '/PATTERN1/!p' FILE