What would happen when using $1
, $2
... in the END
block, like:
awk '{print $3}END{print $1 $2}'
I found that $1
and $2
retain the values from the last record. Is this behaviour guaranteed by the standard or is it implementation-specific?
END pattern: means that Awk will execute the action(s) specified in END before it actually exits.
You generally use BEGIN and END clauses in awk when you do want certain actions before and after the actual processing on the file happens respectively. So with this logic the statements/actions within them are executed just once for the given input file.
Use NR == 1 to get the first line, and END to get the last line.
Find out the last line of a file: Using sed (stream editor): sed -n '$p' fileName. Using tail: tail -1 fileName. using awk: awk 'END { print }' fileName.
Checking the docs we see that it is implementation-specific:
Traditionally, due largely to implementation issues, $0 and NF were undefined inside an END rule. The POSIX standard specifies that NF is available in an END rule. It contains the number of fields from the last input record. Most probably due to an oversight, the standard does not say that $0 is also preserved, although logically one would think that it should be. In fact, all of BWK awk, mawk, and gawk preserve the value of $0 for use in END rules. Be aware, however, that some other implementations and many older versions of Unix awk do not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With