Home > bash > sed – Print lines that do not match a pattern.

sed – Print lines that do not match a pattern.

I am checking that a file containing questions have question marks. So I need to print out all the lines that do not have question marks. (NB. One question per line.)


sed -n '/?/!p' questions.txt | less

From http://www.grymoire.com/Unix/Sed.html#uh-32

Reversing the restriction with !
Sometimes you need to perform an action on every line except those that match a regular expression, or those outside of a range of addresses. The “!” character, which often means not in Unix utilities, inverts the address restriction. You remember that

sed -n ‘/match/ p’

acts like the grep command. The “-v” option to grep prints all lines that don’t contain the pattern. Sed can do this with

sed -n ‘/match/ !p’ </tmp/b


Categories: bash Tags:
  1. Warren
    May 1, 2014 at 11:37 pm

    I had a situation in which I had to print out the line BEFORE a line that did not match a pattern!

    Essentially, I have a file that has hostnames, followed by a list of usernames on that host.

    So I needed a list of hosts that a user does NOT have an account:

    SERVER: host1.mydomain
    SERVER: host2.mydomain
    SERVER: host3.mydomain

    So I want a list of servers that do NOT have fred as a user:

    egrep “SERVER|fred” filename | sed -n ‘${/fred/!p};N;/fred/!{P;D}’

    If the last line does NOT have fred, print it: ${/fred/!p}
    Append the next line to the pattern buffer: N
    If that line does not have fred ( /fred/! ), then print up to the first carriage return (P), and delete up to the first carriage return and restart the cycle (D).

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: