Why does awk 'END{print}' file
return an empty string?
I've checked the file and it does not end with empty line.
I'm on HP-UX.
Why does awk 'END{print}' file
return an empty string?
I've checked the file and it does not end with empty line.
I'm on HP-UX.
END
means "execute the given block after the file has been processed", there is no data to print associated to it.
If you want to process the last line, save each line in a variable in a default block and then process the variable in the end block.
awk '{ last_line = $0; } END { /* do something with last_line */}' file
Or use tail
before feeding data to awk
:)
echo "a" | awk 'END {print}'
returns a
. –
Rockaway awk
, now kind of deprecated. –
Rockaway From The GNU Awk guide - 7.1.4.2 Input/Output from BEGIN and END Rules
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.
So, in general, END
now contains the last $0
, whereas in your [old] awk version it does not.
For example, my GNU Awk does work in the "new" way:
$ awk --version
GNU Awk 4.1.0, API: 1.0
$ seq 10 | awk 'END {print}'
10
echo 'a b c' | awk '{last=$0} END{$0=last; print NF, $0, $1}' file
outputs 3 a b c a
? –
Colton END
means "execute the given block after the file has been processed", there is no data to print associated to it.
If you want to process the last line, save each line in a variable in a default block and then process the variable in the end block.
awk '{ last_line = $0; } END { /* do something with last_line */}' file
Or use tail
before feeding data to awk
:)
echo "a" | awk 'END {print}'
returns a
. –
Rockaway awk
, now kind of deprecated. –
Rockaway © 2022 - 2024 — McMap. All rights reserved.
'{print}'
) work correctly? – Mannsawk '{x=$0}END{print x}' File
– Gaiseric