Low Orbit Flux Logo 2 F

How to Exclude in Grep

You can use the grep command to exclude a string like this:



grep -v test123  data1.txt

This was the most simple example.

There are a lot of other nice options that can be used:

-v invert / exclude
-e multiple search patterns
-w whole words
-i case insensitive
-E extended regular expressions

You can do a case insensitive match with a “-i” like this. This is the my most common use case.



grep -vi test123  data1.txt

Using a “-w” will match actual words. The pattern will need white space on both ends. This way it won’t just match any text with the pattern in the middle.



grep -wv test123  data1.txt

You can match tow different strings by separating them with the “or” operator “|”. It needs to be escaped with a “" unless you use extended regex support.



grep -vi "bob\|greg" /etc/passwd

Here is an example that would match three strings.



grep -vi "bob\|greg\|steve" /etc/passwd

If you don’t want to have to use escape characters for “|” then you can specify the extended regex option with “-E” like this.



grep -Evi "bob|greg|steve"

You can also specify multple strings to exclude using the “-e” option more than once.



grep -wv -e bob -e greg /etc/passwd

Exclude lines that start with this pattern:



grep -v "^abc"

Excluding Files and Directories with Grep

-r recursive
-R recursive, follow symlinks

Search “/home/user1” for any file conaining “project” but exclude “/opt/data”



grep -R --exclude-dir=data project /opt

Exclude multiple directories:



grep -R --exclude-dir={data,conf} project /opt

Great for excluding things like this:



grep -R --exclude-dir={dev,sys,proc} project /

Exclude files matching a glob ( ex .dat and .txt files ):



grep -rl --exclude=*.{dat,txt} linuxize *