How to Exclude using Grep Command
The grep command-line tool is enormously helpful for searching through text data for lines and snippets that match a particular string, character, phrase, or regular expression. While most users of grep are for sorting data for syntactic matches, what if you wish to exclude a word or string using grep instead? Excluding line matches with grep is just as helpful as discovering and printing matches in grep, so let’s explore how to exclude string matches and exclude words with grep.
Obviously, you’ll want to have some command line knowledge and exposure to grep to find this helpful. If you wish to follow along, you may launch the Terminal program and try it out yourself. Since grep is an OS neutral application, you may use the exclusion method with Mac OS, Linux, Unix, or anything else you have that utilizes grep.
How to Exclude a Single Word with grep Command
The most basic approach to exclude lines with a string or syntactic match is by using grep and the -v parameter.
For example, let’s imagine we’re using cat to display a file at the command line, but we want to omit any lines that have the phrase “ThisWord”, then the syntax would look as follow:
cat example.txt | grep -v "ThisWord"
The result will be the example.txt text file but omitting every line that includes a string match with “ThisWord”.
You may also use grep directly on files and exclude line matches based on terms or syntax, like so:
grep -v "ThisWord" example.txt
Use whatever works best for your unique routine.
How to Exclude Multiple Strings or Words with grep command
Now that you know how to exclude matches for a single word, the next natural question is about omitting several words using grep. That’s just as straightforward, and there are a couple of other methods to achieve this utilizing the -v option as well as the -e flag.
First, we take the preceding example of using cat on a file piped to grep, and eliminate any lines matching two terms; “Word1” and “Word2”, this would look like the following:
cat example.txt | grep -v -e "Word1" -e "Word2"
Any lines that include “Word1” or “Word2” will be omitted from the printed results.
You can also use grep directly on files same as previously as well:
grep -v -e "Word1" -e "Word2" example.txt
Another option is to split what to exclude using grep by using a pipe to separate each match, like so:
grep -Ev "word1|word2" example.txt
If you try out any of these choices on an example text file, you will see the result is the same regardless of the technique you pick, each omitting lines that have the specified phrases, syntax, words, or text match.