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:
The purpose of the action is to tell awk what to do once a match for the pattern is found
.next;
suppress the printing of the matching line, as print
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
match()
call inside if()
in the default action, but why didn't this variant work?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;
}