Untitled Document
printf Command

The printf command is similar to echo command which displays / print ouput on the terminal . The echo command is pretty simple and easy to use , but when it comes to formatting output with echo is really a nightmare for a programmer . The printf command has various formatting option while printing output .

1. Basic Example -

Run below printf command .

   printf " Hellow World !" 
   output - Hello World !  

2. Printing ouptput in multiple lines -

To print output in New line - use new line character \n .

   printf "Hello \nWorld !"
   output - 
   Hello
   World !

2. Formatting output with printf -

Save below code in format.ksh script and run the script to see the formatted output .

#/bin/ksh 
divider===============================
divider=$divider$divider

header="\n %-10s %8s %10s %11s\n"
format=" %-10s %08d %10s %11.2f\n"

width=43

printf "$header" "ITEM NAME" "ITEM ID" "COLOR" "PRICE"

printf "%$width.${width}s\n" "$divider"

printf "$format" \
Triangle 13  red 20 \
Oval 204449 "dark blue" 65.656 \
Square 3145 orange .7  
OUTPUT : 


ITEM NAME   ITEM ID      COLOR       PRICE
===========================================
 Triangle   00000013        red       20.00
 Oval       00204449  dark blue       65.66
 Square     00003145     orange        0.70
Untitled Document