gawk: Using BEGIN/END
1
1 7.1.4.1 Startup and Cleanup Actions
1 ...................................
1
1 A 'BEGIN' rule is executed once only, before the first input record is
1 read. Likewise, an 'END' rule is executed once only, after all the
1 input is read. For example:
1
1 $ awk '
1 > BEGIN { print "Analysis of \"li\"" }
1 > /li/ { ++n }
1 > END { print "\"li\" appears in", n, "records." }' mail-list
1 -| Analysis of "li"
1 -| "li" appears in 4 records.
1
1 This program finds the number of records in the input file
1 'mail-list' that contain the string 'li'. The 'BEGIN' rule prints a
1 title for the report. There is no need to use the 'BEGIN' rule to
1 initialize the counter 'n' to zero, as 'awk' does this automatically
1 (⇒Variables). The second rule increments the variable 'n' every
1 time a record containing the pattern 'li' is read. The 'END' rule
1 prints the value of 'n' at the end of the run.
1
1 The special patterns 'BEGIN' and 'END' cannot be used in ranges or
1 with Boolean operators (indeed, they cannot be used with any operators).
1 An 'awk' program may have multiple 'BEGIN' and/or 'END' rules. They are
1 executed in the order in which they appear: all the 'BEGIN' rules at
1 startup and all the 'END' rules at termination. 'BEGIN' and 'END' rules
1 may be intermixed with other rules. This feature was added in the 1987
1 version of 'awk' and is included in the POSIX standard. The original
1 (1978) version of 'awk' required the 'BEGIN' rule to be placed at the
1 beginning of the program, the 'END' rule to be placed at the end, and
1 only allowed one of each. This is no longer required, but it is a good
1 idea to follow this template in terms of program organization and
1 readability.
1
1 Multiple 'BEGIN' and 'END' rules are useful for writing library
1 functions, because each library file can have its own 'BEGIN' and/or
1 'END' rule to do its own initialization and/or cleanup. The order in
1 which library functions are named on the command line controls the order
1 in which their 'BEGIN' and 'END' rules are executed. Therefore, you
1 have to be careful when writing such rules in library files so that the
1 order in which they are executed doesn't matter. ⇒Options for
1 more information on using library functions. ⇒Library Functions,
1 for a number of useful library functions.
1
1 If an 'awk' program has only 'BEGIN' rules and no other rules, then
1 the program exits after the 'BEGIN' rules are run.(1) However, if an
1 'END' rule exists, then the input is read, even if there are no other
1 rules in the program. This is necessary in case the 'END' rule checks
1 the 'FNR' and 'NR' variables.
1
1 ---------- Footnotes ----------
1
1 (1) The original version of 'awk' kept reading and ignoring input
1 until the end of the file was seen.
1