Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are fields defined in the END block in AWK?

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?

like image 205
Mosty Amine Avatar asked Aug 01 '16 12:08

Mosty Amine


People also ask

What is END in awk?

END pattern: means that Awk will execute the action(s) specified in END before it actually exits.

Why BEGIN is used in awk?

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.

How do you print first and last line in awk?

Use NR == 1 to get the first line, and END to get the last line.

How do I print the last line in awk?

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.


1 Answers

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.

like image 99
Juan Diego Godoy Robles Avatar answered Oct 06 '22 07:10

Juan Diego Godoy Robles