Linux Shell Scripting Tutorial (LSST) v1.05r3
Prev
Chapter 7: awk Revisited
Next

Use of Format Specification Code

$ cat > bill4
BEGIN {
  printf "Bill for the 4-March-2001.\n"
  printf "By Vivek G Gite.\n"
  printf "---------------------------\n"
}

{
  total = $3 * $4
  recno = $1
  item = $2
  gtotal += total
  printf "%2d %-10s Rs.%7.2f\n", recno, item, total
}

END {
  printf "---------------------------\n"
  printf "\tTotal Rs. %6.2f\n" ,gtotal
  printf "===========================\n"
}

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 ,

$ cat > prf_demo
{
na = $1
printf "|%s|", na
printf "|%10s|", na
printf "|%-10s|", na
}

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|", naPrint God Word as Right justified. 
printf "|%-10s|", naPrint 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 operatorUse forExampleEquivalent to
+=Assign the result of additiona += 10
d += c
a = a + 10
a = a + c
-=Assign the result of subtractiona -= 10
d -= c
a = a - 10
a = a - c
*=Assign the result of multiplicationa *= 10
d *= c
a = a * 10
a = a * c
%=Assign the result of moduloa %= 10
d %= c
a = a % 10
a = a % c


Prev
Home
Next
Use of printf statement
Up
if condition in awk