Skip to content Skip to navigation

Grep Invert Match

Today I learned about the -v flag for grep. The -v, or --invert-match, flag, returns all lines that do not match your regular expression.

Let's say you have a long list of items, and you want to narrow it down to the ones that are not orange. I have banged my head against trying to do this with sed multiple times (as my search history will attest), and it turns out to be so much easier with grep.

orange bicycle
orange sweater
green banana
orange basketball
blue bandana
orange you glad I stopped there?

If that list is in a file called list.txt, run:

grep -v "^orange" list.txt

and it will return:

green banana
blue bandana

Pretty spiffy!

Categories: 
Tags: 

Comments

Cool, so I could find all files that are not jpgs in a directory by something like:

ls ./ | grep -v "\.jpg"

That is spiffy!

% awk /^green/,/^blue/ list.txt
green banana
orange basketball
blue bandana

Regular Expressions

Add new comment