awktutorial/02-script-structure.awk

35 lines
1.3 KiB
Awk
Executable File

#!/usr/bin/awk -f
# https://www.grymoire.com/Unix/Awk.html
# repeating for emphasis, awk moves line by line through the lines of
# an input file, processing each line in turn.
# but sometimes you want to do something first, before you start
# poring over the file, and maybe also something after you're done
# with the file. you can do these with BEGIN and END blocks.
# the script below will run exactly like the 01.awk script, except that
# it will print "BEGINNING OF THE SCRIPT" before processing all the
# lines of input, and "END OF THE SCRIPT" once the lines have all been
# processed.
BEGIN { print "BEGINNING OF THE SCRIPT" }
{ print }
END { print "END OF THE SCRIPT" }
# what are common use cases of the BEGIN and END blocks?
# BEGIN - awk is often used to generate data reports, and the BEGIN
# block is a good place to print a header row that will appear once
# before the data.
# the BEGIN block is also a good place to initialize variables and
# functions, as you'll learn about later (although functions can
# be defined anywhere, even outside of blocks).
# END - in reports, the END block is often where you will print
# summary statistics that were calculated in the main body of the
# script; or to generally do *something* with the results of the
# script.