Inverse regex in AWK

awkregular expression

I am trying to filter out the lines containing a particular word. The regex is command line input to the script.

$0 ~ regex {
//Do something.
}

Sample input is:

**String** **number**
domain  1
domain  2
bla     3

So, from the above input, user can say – filter out the rows which have word "domain".

What I've tried:

regex = "\?\\!domain" 

(negative lookahead).

But this regex is filtering out every row. Not just the rows with word "domain".

Best Answer

For given input file input containing the following:

domain
demesne

To filter for lines containing domain:

$ awk '/domain/ { print }' input
domain

To filter for lines not containing domain:

$ awk '!/domain/ {print }' input
demesne

For filtering based on the field rather than the entire line, we can try the following for the new given input file:

example www.example.com
exemplar www.example.net

To filter out lines where the first field contains example:

$ awk '$1 !~ /example/ { print }' input
exemplar www.example.net

In your question, you used $0 which is the entire line rather than the first field.

Related Question