2

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:

Victor Sergienko
  • 13,115
  • 3
  • 57
  • 91
  • I tried a very similar form on different data: `awk '/424/ {if (NR==3) {print;next;}print NR;next;} {print "no";}'` Output was as expected (Line numbers were printed if "424" was in the line except on line 3 where the line was printed. "no" was printed otherwise.) Also gawk. – zzxyz May 14 '18 at 22:41
  • I assume `fields[1]` is some..construct I'm not aware of that makes sense. `$1`, which you used above would of course be the normal way to the print the first column. – zzxyz May 14 '18 at 22:44
  • 1
    Broke the MCV when minimizing it. Let me fix it. – Victor Sergienko May 14 '18 at 22:55

1 Answers1

4

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;
}
glenn jackman
  • 238,783
  • 38
  • 220
  • 352