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

Use of printf statement

Next example shows the use of special printf statement

$ cat > bill3
    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 "%d %s Rs.%f\n", recno, item, total
    #printf "%2d %-10s Rs.%7.2f\n", recno, item, total

   printf "---------------------------\n"
   printf "Total Rs. %f\n" ,gtotal
   #printf "\tTotal Rs. %7.2f\n" ,gtotal
   printf "===========================\n"

Run it as follows:
$ awk -f bill3 inven
Bill for the 4-March-2001.
By Vivek G Gite.
1 Pen Rs.100.000000
2 Pencil Rs.20.000000
3 Rubber Rs.10.500000
4 Cock Rs.91.000000
Total Rs. 221.500000

In above example printf statement is used to print formatted output of the variables or text. General syntax of printf as follows:
printf "format" ,var1, var2, var N

If you just want to print any text using try printf as follows
printf "Hello"
printf "Hello World\n"

In last example \n is used to print new line. Its Part of escape sequence following may be also used:
\t   for tab
\a  Alert or bell
\"  Print double quote etc

For e.g. printf "\nAn apple a day, keeps away\t\t\tDoctor\n\a\a"
It will print text on new line as :
An apple a day, keeps away Doctor
Notice that twice the sound of bell is produced by \a\a. To print the value of decimal number use %d as format specification code followed by the variable name. For e.g. printf "%d" , no1

It will print the value of no1. Following table shows such common format specification code:

Format Specification CodeMeaningExample
  isminor = "y"
  printf "%c" , isminor
%dDecimal number such as 10,-5  etc{
   n = 10
   printf "%d",n
%xHexadecimal number such as 0xA, 0xffff etc{
   n = 10
   printf "%x",n
%sString such as "vivek", "Good buy"{
   str1 = "Welcome to Linux!"
   printf "%s", str1
   printf "%s", "Can print ?"

To run above example simply create any awk program file as follows

$ cat > p_demo
n = 10
printf "%d", n
printf "\nAn apple a day, keeps away\t\t\tDoctor\n\a\a"

Run it as
$ awk -f p_demo
An apple a day, keeps away Doctor

Write awk program to test format specification code. According to your choice.

User Defined variables in awk
Use of Format Specification Code