Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In awk, can you use a pattern AND an END block together?

Tags:

awk

In awk, you can perform an action for a given pattern, like:

echo foo | awk '/foo/ {print "foo"}'

or you can perform an action at the end of the input, like:

echo foo | awk 'END {print "END"}'

But it does not appear to be possible to do both, like:

# echo foo | awk '/foo/ || END {print "foo or END"}'
awk: syntax error at source line 1
 context is
    /foo/ || >>>  END <<<  {print "foo or END"}
awk: bailing out at source line 1

Is this possible?

like image 626
Brian Avatar asked Jan 26 '23 22:01

Brian


1 Answers

No. Do this instead:

awk '
/foo/ { prtInfo() }
END   { prtInfo() }
function prtInfo() { print "foo or END" }
'
like image 63
Ed Morton Avatar answered Jan 30 '23 01:01

Ed Morton