Search code examples
nawk

"nawk if else if else" not working


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.


Solution

  • 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
    $