1

ok, this is most probably going to sound like a stupid question to you, but I can't make it work and really don't know what I do wrong here even after reading quite a few nawk/awk help sites:

    $ echo -e "hey\nthis\nworld" | nawk '{ if ( $1 !~ /e/ ) { print $0; } else if ($1 !~ /o/ ) { print $0; } else { print "condition not mached"; } }'
    hey
    this
    world
    $ 

I'd prefer to have it on one line but also tried on multiple lines as seen in various examples:

    $ echo -e "hey\nthis\nworld" | nawk '{ 
    if ( $1 !~ /e/ )
    print $0;
    else if ($1 !~ /o/ )
    print $0;
    else
    print "condition not matched"
    }'
    hey
    this
    world
    $ 

Thanks in advance for helping a nawk-newbie!

I simply want to have only printed lines not containing a certain pattern, here "e" or "o". The final else I only added for testing-purpose.

hermann
  • 13
  • 2

2 Answers2

0

You can make your life a lot easier by simply doing:

echo "hey\nthis\nworld" | nawk '$1 !~ /e|o/'

What is going wrong in your case is:

$ echo -e "hey\nthis\nworld" | nawk '{ 
if ( $1 !~ /e/ ) #'this' and 'world' satisfy this condition and so are printed 
print $0; 
else if ($1 !~ /o/ ) #Only 'hey' falls through to this test and passes and prints
print $0;
else
print "condition not matched"
}'
hey
this
world
$ 
Ell
  • 927
  • 6
  • 10
0

FWIW the right way to do this is with a character list inside a ternary expression:

awk '{ print ($1 ~ /[eo]/ ? $0 : "condition not matched") }'

Going forward if you tag your questions with awk instead of just nawk (which is an old, non-POSIX and relatively redundant awk variant) they'll reach a much wider audience.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185