How To Exclude In Grep?

grep is a very powerful and useful tool used to search and match different terms inside files or directories. The grep is regularly used with a search term that is expected to match but in some cases, we may need to exclude the specified term or terms. In this tutorial, we examine how to exclude in grep with the simple term, word, multiple terms, etc.

Exclude with Grep

In order to exclude specified terms, the inverted match is used for the grep. The -V or --invert-match option is used to enable the inverted match. In the following example, we exclude those lines with the bash for the /etc/passwd file.

$ grep -v bash /etc/passwd

Exclude Word

By default, the grep matches the specified term as characters, but we can exclude words that are separated characters from other characters with spaces and other characters like point, etc. The -w is used to interpret the term as a word.

$ grep -v bash /etc/passwd

Exclude Case Insensitive

The grep command works as case-sensitive. But in some cases, we may need to search case insensitive in order to exclude matches. The -i is used to disabling case-sensitive matches.

$ grep -v -i bash /etc/passwd

Exclude Multiple Patterns

Another useful option to exclude grep match is using multiple terms. We can exclude multiple terms in a single grep execution. The -e option is used multiple times in order to provide multiple exclude patterns.

$ grep -v -e bash -e zsh -e csh /etc/passwd

Exclude Directories and Files

During the grep excluded usage for file contents, we can search for recursively. But we may need to exclude some directories or files for the exclude search.

$ grep -r -v --exclude-dir={home,var,etc} ismail /

Exclude for Line Start

We can specify a term to exclude from the line start. In the following example, we exclude lines starting with “linuxtect”.

$ grep -r -v "^linuxtect" /etc/

Exclude for Line End

We can also exclude the line end for the specified term. In the following example, we exclude those lines that end with the “linuxtect”.

$ grep -r -v "linuxtect$" /etc/

Leave a Comment