Awk END behavior on HP-UX

Why is awk 'END{print}' file returning an empty string?

I checked the file and it does not end with an empty line.

I'm on HP-UX.

+1
unix shell awk hp-ux
source share
2 answers

END means "execute the given block after processing the file", there is no print data associated with it.

If you want to process the last line, save each line in a variable in the default block, and then process the variable in the final block.

 awk '{ last_line = $0; } END { /* do something with last_line */}' file 

Or use tail before submitting data to awk :)

+3
source share

From the GNU Awk Manual - 7.1.4.2 Input / Output from BEGIN and END Rules

Traditionally, mainly due to implementation problems, $ 0 and NF were undefined inside the END rule. The POSIX standard indicates that NF is available in the END rule. It contains the number of fields from the last entry entry. Most likely, due to oversight, the standard does not say that $ 0 is also preserved, although logically one should think what it should be. In fact, all BWK awk, mawk and gawk save the value $ 0 for use in END rules. However, keep in mind that some other implementations and many older versions of Unix awk do not.

So, in the general case, END now contains the last $0 , whereas in your [old] awk version this is not so.

For example, my GNU Awk works in a "new" way:

 $ awk --version GNU Awk 4.1.0, API: 1.0 $ seq 10 | awk 'END {print}' 10 
+5
source share

All Articles