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".

  • 1
    Seems awk -v p="domain" '$0 !~ p' should work ... ? – steeldriver Oct 25 '16 at 16:24
  • just few minutes back this was posted - unix.stackexchange.com/questions/318839/… awk doesn't support lookarounds... – Sundeep Oct 25 '16 at 16:34
  • @Sundeep, missed that post..my requirement is exactly same – Venkat Teki Oct 25 '16 at 16:39
  • 1
    but why do you need lookaround for the question described? if you need to print lines containing domain, use awk '/domain/{print}'.. if you do not want lines containing domain, use awk '!/domain/{print}' – Sundeep Oct 25 '16 at 16:41

For given input file input containing the following:


To filter for lines containing domain:

$ awk '/domain/ { print }' input

To filter for lines not containing domain:

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.