Are fields defined in the END block in AWK?

2019-06-17 06:34发布

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?

1条回答
孤傲高冷的网名
2楼-- · 2019-06-17 06:54

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.

查看更多
登录 后发表回答