printf - Printing with format
printf formats and prints its arguments according to format, a character string which contains three types of objects: plain characters, which are simply copied to standard output, character escape sequences which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive value.
To Get Zero Leading Number
$ printf "%03d" 1
$ 001
To Print Line by Line Including Speces in Terminal
Interactive script in terminal sometime requires to clear terminal's face and print line by line without flickering the terminal's face. In that case, using printf "%-*.*s%s\n" "$MINCOL" "$MAXCOL" "string of the line" is a trick.
For breaking down, %-*.*s is for width i.e., minimum number of columns and maximum number of columns. In above example, "$MINCOL" and "$MAXCOL" are variables of minimum and maximum number of columns resprectively. Furthermore, %s is "string of the line" and \n is next line.
For more explanation, this page of stackoverflow.com is very clear.
The following explanation is copied from above page. It is based on man page for printf aligned with ISO C Standard The credit goes to Peter - Reinstate Monica.
Let's start with a simple printf("%s", "abc"). It will print the string abc.
printf("%8s", "abc") will print abc, including 5 leading spaces: 8 is the "field width". Think of a table of data with column widths so that data in the same column is vertically aligned. The data is by default right-aligned, suitable for numbers.
printf("%-8s", "abc") will print abc , including 5 trailing spaces: the minus indicates left alignment in the field.
It is important that this is a minimum field width: In spite of the field width being only 8, printf("%-8s", "1234567890") will print all 10 characters, without any spaces.
Now for the star: printf("%-*s", 8, "abc") will print the same as the ordinary printf("%-8s", "abc"). The star indicates that the field width (here: 8) will be passed as a parameter to printf. That way it can be changed programmatically.
Now for the "precision", that is: printf("%-*.10s", 8, "1234567890123") will print only 1234567890, omitting the last three characters: the "precision" is the maximum field width in case of strings. This is one of the rare cases (apart from rounding, which is also controlled by the precision value) where data is truncated by printf.
And finally printf("%-*.*s", 8, 10, "1234567890123") will print the same as before, but the maximum field width is given as a parameter, too.
Note: the syntax in above explanation, printf() is of many programing language especially C. For bash or dash scripting, the syntax is printf "%s" "abc" without parentheses.

Comments
Post a Comment