I am looking to have a awk regular expression that can give all strings not matching a particular word.

using /^((?!word \+).)*/ works in java but does not work in AWK.

Get compilation failed error, escaping the brackets fixes the compilation error, but the regular expression matching is not correct.

It would be great if any one can help with a awk regular expression .

I can not use string" !~ /regex/

I need to use string" ~ /regex/ regex shuould pass for all string but for a specific string.

Strings containing domain should be filtered out. Input

This is domain test
This is do test
This is test


This is do test
This is test

Need to do with regular expression only. Can not change the Awk code

in AWK its like string" ~ /regex/

so can only pass a regex to achieve this.

  • if you add sample input and expected output, perhaps there might be a workaround... or use perl – Sundeep Oct 25 '16 at 16:09
  • 1
    "I can not use "string" !~ /regex/" Why not? What is the actual problem being solved? – Kaz Oct 25 '16 at 16:11
  • The awk code is fixed. I can only pass regular expression to ignore few strings – kshitij Oct 25 '16 at 16:21

The way you do this in awk is to write a pattern that matches what you want to exclude, and make its action next. That leaves the lines to process which are the negation of the pattern which you are trying to achieve.

Something like this:

/regex/{ next; }
{ print; }


awk -v re="^([^d]|d*d[^do]|[do]*o(d*d[^do]|[^dm])|[dom]*m(d*d[^do]|[do]\
[^dm])|[^da])|[^di])|[^dn]))*[domai]*$" '$0 ~ re'

That only works for strings (like domain here) where all the characters are different.


awk does not support PCRE (Perl Compatible Regular Expression), so you can not use any zero width lookarounds like the negative lookahead you are using, (?!word +).

awk's Regex engine only supports ERE (Extended Regular Expression). You need to incorporate all logics in there or you can break up the logic to meet your need. Also look at the builtin functions of awk, check if they are of any help in the regard.

  • Thanks! Now I know why it does not work. I can not change the logic, as the awk code is fixed(out of control), I can only change the regex. – kshitij Oct 25 '16 at 16:18

While Thomas Dickey's answer is clever, there is a right way to do this:

awk '!/domain/ {print}' <<EOF
This is domain test
This is do test
This is test

This is do test
This is test
  • The OP said they can't use string !~ /regex/ – Stéphane Chazelas Aug 30 '18 at 21:51
  • The OP said they tried to use a ! in a way that didn't work. This demonstrates the correct way to use it. I don't see what your issue is. – Bruno Bronosky Aug 31 '18 at 1:28

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.