Technology

#How To Use Negative Matching With grep In Linux (Print Lines That Don’t Match)

“How To Use Negative Matching With grep In Linux (Print Lines That Don’t Match)”

Bash Shell

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.

If you liked the article, do not forget to share it with your friends. Follow us on Google News too, click on the star and choose us from your favorites.

For forums sites go to Forum.BuradaBiliyorum.Com

If you want to read more like this article, you can visit our Technology category.

Source

Related Articles

Leave a Reply

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

Back to top button
Close

Please allow ads on our site

Please consider supporting us by disabling your ad blocker!