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.
Basic BEGIN Statement
Issue the following command:
awk 'BEGIN {print "NUMBER ITEM QUANTITY PRICE"}' /sharewiz/awk/test2.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}' /sharewiz/awk/test2.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}' /sharewiz/awk/test2.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}' /sharewiz/awk/test2.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.1594805433.txt.gz · Last modified: 2020/07/15 09:30 by 127.0.0.1