| Linux Shell Scripting Tutorial (LSST) v1.05r3 | ||
|  Chapter 7: awk Revisited | ||
|  | ||
| $ cat > bill4 | 
Run it as
 $ awk -f bill4 inven 
 Bill for the 4-March-2001.
 By Vivek G Gite.
 ---------------------------
 1 Pen       Rs. 100.00
 2 Pencil   Rs. 20.00
 3 Rubber Rs. 10.50
 4 Cock    Rs. 91.00
 ---------------------------
 Total      Rs. 221.50
 =============== 
From the above output you can clearly see that printf can format the output. Let's try to understand formatting of printf statement. For e.g. %2d, number between % and d, tells the printf that assign 2 spaces for value. Same way if you write following awk program ,
| 
 | 
Run it as follows (and type the God)
 $ awk -f prf_demo
 God
 |God|
 |      God|
 |God      |
(press CTRL + D to terminate)
| printf "|%s|", na | Print God as its | 
| printf "|%10s|", na | Print God Word as Right justified. | 
| printf "|%-10s|", na | Print God Word as left justified. (- means left justified) | 
Same technique is used in our bill4 awk program to print formatted output. Also the statement like gtotal += total, which is equvalent to gtotal = gtotal + total. Here += is called assignment operator. You can use following assignment operator:
| Assignment operator | Use for | Example | Equivalent to | 
| += | Assign the result of addition | a += 10 d += c | a = a + 10 a = a + c | 
| -= | Assign the result of subtraction | a -= 10 d -= c | a = a - 10 a = a - c | 
| *= | Assign the result of multiplication | a *= 10 d *= c | a = a * 10 a = a * c | 
| %= | Assign the result of modulo | a %= 10 d %= c | a = a % 10 a = a % c | 
| Use of printf statement | if condition in awk | |