awk:begin_and_end
This is an old revision of the document!
Table of Contents
AWK - BEGIN and END
Actions can be specified to take place prior to the actual start of processing or after it has been completed with BEGIN and END statements respectively.
- BEGIN statements are most commonly used to establish variables or display a header.
- END statements, on the other hand, can be used to continue processing after the program has finished.
Assuming a file, test.txt, exists with the following contents:
10 Peter Terence Roux 45 11 Virginia Genevive Roux 45 12 Felix Devon Roux 5 13 David Bruce Stevenson 48 14 Bob James Smith 16 48 Adam Winter Ridley 23
Basic BEGIN Statement
Issue the following command:
awk 'BEGIN {print "NUMBER ITEM QUANTITY PRICE"}' test.txt
which will display something like:
NUMBER ITEM QUANTITY PRICE
This would be more useful when run as:
awk 'BEGIN {print "NUMBER ITEM QUANTITY PRICE"}{print NR,$1,$2,$3}' test.txt
which will display something like:
NUMBER ITEM QUANTITY PRICE 1 pens 10 1.99 2 pencils 20 3.99 3 staplers 5 8.99 4 rulers 12 2.50
- The BEGIN has allowed the header to be added to the output.
- The NR variable used in the 2nd print numbers each line. It is a built-in variable of AWK.
Basic END Statement
Issue the following command:
awk '{x=x+($2*$3)} END {print "Total Value of Inventory: "x}' test.txt
which will display something like:
Total Value of Inventory: 174.65
This would be more useful when run as:
awk '{x=x+($2*$3)} {print $1,"QTY: "$2,"PRICE:"$3,"TOTAL: "$2*$3} END {print "Total Value of Inventory: " x}' test.txt
which will display something like:
pens QTY: 10 PRICE:1.99 TOTAL: 19.9 pencils QTY: 20 PRICE:3.99 TOTAL: 79.8 staplers QTY: 5 PRICE:8.99 TOTAL: 44.95 rulers QTY: 12 PRICE:2.50 TOTAL: 30 Total Value of Inventory: 174.65
- The END has allowed a total line to be added to the output.
- It is only run at the end.
awk/begin_and_end.1609945827.txt.gz · Last modified: 2021/01/06 15:10 by peter