Search code examples
shellawkgawk

gawk: why doesn't "next;" suppress lines matching a pattern?


I have the following awk program:

/.*needle.*/
{
    if ($0 != "hay needle hay")
    {
        print "yay: ", $1;
        next;
    }

    print "ya2";
    next;
}

{
    print "no";
    next;
}

I run it as gawk -f test.awk < some.log > out.log in GNU Awk 4.2.1, API: 2.0.

some.log:

hay hay hay
hay needle hay
needle
hay hay
hay
hay

out.log:

yay:  hay         
hay needle hay    
ya2               
needle            
yay:  needle      
yay:  hay         
yay:  hay         
yay:  hay         

I expect it only to only print "ya2-new line-yay: needle".

This raises questions:


Solution

  • You seem to be a fan of the Allman indentation style. I assume the if ($0 != ... block is only supposed to run where the record matches needle -- you need to put the opening brace on the same line as the pattern.

    /.*needle.*/ {
        if ($0 != "hay needle hay")
        {
            print "yay: ", $1;
            next;
        }
    
        print "ya2";
        next;
    }
    

    Output:

    no
    ya2
    yay:  needle
    no
    no
    no
    

    In awk, newline is a terminator, like semi-colon.

    What you have now is:

    # if the line matches "needle", print it verbatim
    /.*needle.*/     
    
    # And **also**, for every line, do this:
    {
        if ($0 != "hay needle hay")
        {
            print "yay: ", $1;
            next;
        }
    
        print "ya2";
        next;
    }