Linux Shell Scripting Tutorial (LSST) v1.05r3 | ||
Chapter 7: awk Revisited | ||
|
Next example shows the use of special printf statement
$ cat > bill3 |
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:
Syntax:
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 Code | Meaning | Example |
%c | Character | { isminor = "y" printf "%c" , isminor } |
%d | Decimal number such as 10,-5 etc | { n = 10 printf "%d",n } |
%x | Hexadecimal number such as 0xA, 0xffff etc | { n = 10 printf "%x",n } |
%s | String 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 |
Run it as
$ awk -f p_demo
10
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 |