I read another answer that describes how to use AWK to view the last line of output:
$ seq 42 | awk 'END { print }'
42
So it seems like when the END
block is run the last line is loaded in $0
.
This surprised me because the first line isn't loaded into the BEGIN
block:
$ seq 42 | awk 'BEGIN { print }'
#=> blank
- Is this behavior documentation anywhere? (I searched through the man page but didn't find anything)
Best Answer
The
BEGIN
block is run before any input is processed, so$0
hasn’t been initialised yet.The
END
block doesn’t do anything to$0
, which keeps its last value. In your AWK script, that’s just the last line read, because AWK reads all its input line by line, does its usual field-splitting processing (assigning$0
and so on), but never finds a matching block; but for exampleoutputs 21, not 42, so it’s not the case that “when the
END
block is run the last line is loaded in$0
”.This isn’t documented in the
gawk(1)
manpage, but it is documented inmawk(1)
(for that implementation of AWK obviously):The GNU AWK manual does mention this behaviour:
“BWK
awk
” is Brian Kernighan’sawk
, the “one trueawk
”; it implemented this behaviour in 2005, as documented in itsFIXES
file:That change is visible in the “one true
awk
” history. The latest release of BWKawk
behaves in the same way as GNU AWK: