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:
- Why is the pattern action invoked even on non-matching lines, not the unconditional action?
The purpose of the action is to tell awk what to do once a match for the pattern is found
. - Why doesn't
next;
suppress the printing of the matching line, asprint
is only the "default" action? We have a non-default action here.The next statement forces awk to immediately stop processing the current record and go on to the next record
- I could and did put
match()
call insideif()
in the default action, but why didn't this variant work?