exclude patterns in grep

Grep Exclude Word Pattern

Sometimes you may need to exclude one or more words, or even patterns while using grep to search in a file. In this article, we will look at how to exclude word pattern in grep command.


Grep Exclude Word Pattern

It is very easy to exclude word pattern in grep using -v option, which means inverse match. Here is the syntax for it.

grep -v "unwanted_word" file_path

In the above command, you need to specify the word that you want to exclude after -v option, and then mention path of the file to be searched.

Here is an example to list all lines in file /etc/data.txt which does not contain the word total.

$ sudo grep -v "total" /etc/data.txt

You may pipe the output of above command to search for a word, e.g. column

$ sudo grep -v "total" /etc/data.txt | grep "column"

If you want to match a word but exclude another word, you can use the above command, or the below one.

$ sudo grep "column" /etc/data.txt | grep -V "total"

If you want to exclude multiple words or patterns, you can pipe the output of one grep -v command to the next. Here is the command to exclude both total and sum from our file.

$ sudo grep -v "total" /etc/data.txt | grep "sum"

That’s it. As you can see, it is really easy to exclude one or more words or patterns, using grep -v option.

Also read :

How to Install Fail2ban in CentOS 7
How to Copy File to Multiple Directories in Linux
Shell Script to Loop Through Files in Directory
How to Loop Over Lines of File in Bash
Shell Script To Tar Multiple Files & Directories

Leave a Reply

Your email address will not be published. Required fields are marked *