grep
is a command line search utility for Linux that will print out lines in files that match a pattern or regular expression. It’s also useful to invert matches, which will filter out all lines in a file that contain the given string.
Negative Matching With grep
To use negative matching in grep
, you should execute the command with the -v
or --invert-match
flags. This will print only the lines that don’t match the pattern given.
grep -v "bar" file
Keep in mind though that since grep
isn’t matching anything, there’s no way to use the -o
flag to print “only the matches,” since nothing has technically matched. grep
is able to match multiple times per line, but in this case, it will not matter if there are multiple matches. Any single match will cause grep
to omit the line.
This works with regular expressions (regex) as well and will print any line that files to match the regex.
grep -v "foo ba[rz]" file
While you can write regular expressions that do negative matching, it’s generally easier to invert the match this way.
Alternatively, if you prefer using awk
, you can use the exclamation modifier to invert regex.
awk '!/bar/' file
Negative Matching Filenames
The lowercase -l
flag will cause grep
to print the filenames containing matches instead of the actual matched content. This can be useful when scanning a list of files, but similarly, it’s also useful to invert this sometimes.
The inverse of -l
is the uppercase variant, -L
, which does the opposite:
grep -L "bar" ./*.txt
Make sure you don’t use the -v
flag with -L
to invert the match before printing the files without the match, or you will run into a “double opposites” situation where the match is inverted twice and does not have the intended effect.