7

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?

123
  • 10,778
  • 2
  • 22
  • 45
Mostafa Alayesh
  • 111
  • 1
  • 9
  • I would assume that it is implementation-specific. I don't seen anything in the [spec](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/awk.html) that directly states that the field variables are *not* cleared in an `END` block. – chepner Aug 01 '16 at 12:32
  • I can't find a reference specifically to those fields, but many other variables, like `NR` for example, are specified to have the value of the last record processed, so it wouldn't be crazy to extend that to the field variables as well. – Eric Renouf Aug 01 '16 at 12:33
  • 1
    It is implementation-specific. See for example that in HP-UX `$0` is empty. [awk's END block behaviour on HP-UX](http://stackoverflow.com/q/29970249/1983854) – fedorqui Aug 01 '16 at 12:50

1 Answers1

8

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
  • Correct. As @fedorqui pointed out in his comment [HP-UX awk](http://stackoverflow.com/questions/29970249/awks-end-block-behaviour-on-hp-ux), for example, is one that will not preserve `$0`, etc. in the `END` section. The workaround for the OPs script that I'd like someone with HP-UX to test would, I expect, be `awk '{print $3; last=$0} END{$0=last; print $1, $2}'` – Ed Morton Aug 01 '16 at 13:36
  • @EdMorton that would be interesting to check, since I am curious to see if `$0` gets built in `END` as well. In my GNU awk it does `awk 'END {$0="a b c"; print $1}' file`, but this I don't know if occurs in all awk flavors. – fedorqui Aug 01 '16 at 13:38
  • It **should** work since POSIX says things like `assignment to $0 does blah blah blah`, not `assignment to $0 does blah blah blah except when done in the END section` but I'd like to get confirmation from a test with an awk that doesn't preserve `$0` into the `END` section. – Ed Morton Aug 01 '16 at 13:43