User Tools

Site Tools


awk:begin_and_end

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  Genevieve  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

returns:

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

returns:

NUMBER ITEM QUANTITY PRICE
1 10 Peter Terence
2 11 Virginia Genevieve
3 12 Felix Devon
4 13 David Bruce
5 14 Bob James
6 48 Adam Winter

NOTE:

  • 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

Assuming a file, test2.txt, exists with the following contents:

pens      10    1.99
pencils   20    3.99
staplers   5    8.99
rulers    12    2.50

Issue the following command:

awk '{x=x+($2*$3)} END {print "Total Value of Inventory: "x}' test2.txt

returns:

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}' test2.txt

returns:

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

NOTE:

  • The END has allowed a total line to be added to the output.
    • It is only run at the end.

awk/begin_and_end.txt · Last modified: 2022/06/13 10:40 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki