gawk: I/O And BEGIN/END
1
1 7.1.4.2 Input/Output from 'BEGIN' and 'END' Rules
1 .................................................
1
1 There are several (sometimes subtle) points to be aware of when doing
1 I/O from a 'BEGIN' or 'END' rule. The first has to do with the value of
1 '$0' in a 'BEGIN' rule. Because 'BEGIN' rules are executed before any
1 input is read, there simply is no input record, and therefore no fields,
1 when executing 'BEGIN' rules. References to '$0' and the fields yield a
1 null string or zero, depending upon the context. One way to give '$0' a
11 real value is to execute a 'getline' command without a variable (⇒
Getline). Another way is simply to assign a value to '$0'.
1
1 The second point is similar to the first, but from the other
1 direction. Traditionally, due largely to implementation issues, '$0'
1 and 'NF' were _undefined_ inside an 'END' rule. The POSIX standard
1 specifies that 'NF' is available in an 'END' rule. It contains the
1 number of fields from the last input record. Most probably due to an
1 oversight, the standard does not say that '$0' is also preserved,
1 although logically one would think that it should be. In fact, all of
1 BWK 'awk', 'mawk', and 'gawk' preserve the value of '$0' for use in
1 'END' rules. Be aware, however, that some other implementations and
1 many older versions of Unix 'awk' do not.
1
1 The third point follows from the first two. The meaning of 'print'
1 inside a 'BEGIN' or 'END' rule is the same as always: 'print $0'. If
1 '$0' is the null string, then this prints an empty record. Many
1 longtime 'awk' programmers use an unadorned 'print' in 'BEGIN' and 'END'
1 rules, to mean 'print ""', relying on '$0' being null. Although one
1 might generally get away with this in 'BEGIN' rules, it is a very bad
1 idea in 'END' rules, at least in 'gawk'. It is also poor style, because
1 if an empty line is needed in the output, the program should print one
1 explicitly.
1
1 Finally, the 'next' and 'nextfile' statements are not allowed in a
1 'BEGIN' rule, because the implicit
1 read-a-record-and-match-against-the-rules loop has not started yet.
1 Similarly, those statements are not valid in an 'END' rule, because all
DONTPRINTYET 1 the input has been read. (⇒Next Statement and *noteNextfile
1DONTPRINTYET 1 the input has been read. (⇒Next Statement and ⇒Nextfile
Statement.)
1