Sometimes, we need to filter lines that do not match a specified pattern. In this quick tutorial, we’ll quickly review how to reverse the match for multiple patterns with the grep command. The grep command should be available on any standard Linux installation.
2. Exclude Patterns Passed as Arguments
The grep command matches the input text for one of the specified patterns. First, let’s create a text file:
$ cat << EOF > /tmp/baeldung-grep Time for some thrillin' heroics. You can't take the sky from me. May have been the losing side. Still not convinced it was the wrong one. Every problem is an opportunity in disguise. EOF
For our experiment, we’ll filter lines that do not contain the words the or every.
2.1. Combine Patterns as a Regular Expression
We can form a regular expression that matches either word and invert the match with the -v flag:
$ grep -ivw 'the\|every' /tmp/baeldung-grep Time for some thrillin' heroics.
However, the regular expression may become lengthy and unreadable as the number of patterns grows. To mitigate this, we can specify the patterns individually.
2.2. Specify Multiple Patterns
The -e flag allows us to specify multiple patterns through repeated use. We can exclude various patterns using the -v flag and repetition of the -e flag:
$ grep -ivw -e 'the' -e 'every' /tmp/baeldung-grep Time for some thrillin' heroics.
We have successfully filtered the line that does not contain the specified patterns.
3. Exclude Patterns Mentioned in a File
Alternatively, we can also read the patterns from a file using the -f flag, and invert the match with -v flag. From the manual:
-f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing.
Using a file to hold the patterns allows us to manage a large number of patterns easily and reuse the command from the shell history. Let’s make a file containing only one pattern:
$ echo 'the' > /tmp/baeldung-grep-patterns $ grep -wiv -f /tmp/baeldung-grep-patterns /tmp/baeldung-grep Time for some thrillin' heroics. Every problem is an opportunity in disguise.
Let’s add another entry to the file containing our patterns and run the grep command again:
$ echo 'every' >> /tmp/baeldung-grep-patterns $ grep -wiv -f /tmp/baeldung-grep-patterns /tmp/baeldung-grep Time for some thrillin' heroics.
We have successfully filtered lines not matching any pattern in the specified file. And, we can keep adding more entries to our patterns file as needed.
In this short article, we’ve reviewed various grep flags to see how we can exclude lines matching one of the multiple specified patterns.