Writing Output with More Formatting Control

Problem

You want more control over the formatting and placement of output.

Solution

Use the printf built-in command.

For example:

$ printf '%s = %d
' Lines $LINES
Lines = 24
$

or:

$ printf '%-10.10s = %4.2f
' 'GigaHerz' 1.92735
GigaHerz   = 1.93
$

Discussion

The printf built-in command behaves like the C language library call, where the first argument is the format control string and the successive arguments are formatted according to the format specifications (%).

The numbers between the % and the format type (s or f in our example) provide additional formatting details. For the floating-point type (f), the first number (4 in the 4.2 specifier) is the width of the entire field. The second number (2) is how many digits should be printed to the right of the decimal point. Note that it rounds the answer.

For a string, the first digit is the maximum field width, and the second is the minimum field width. The string will be truncated (if longer than max) or blank padded (if less than min) as needed. When the max and min specifiers are the same, then the string is guaranteed to be that length. The negative sign on the specifier means to left align the string (within its field width). Without the minus sign, the string would right justify, thus:

$ printf '%10.10s = %4.2f
' 'GigaHerz' 1.92735
GigaHerz =   1.93
$

The string argument can either be quoted or unquoted. Use quotes if you need to preserve embedded spacing (there were no spaces needed in our one-word strings), or if you need to escape the special meaning of any special characters in the string (again, our example had none). It’s a good idea to be in the habit of quoting any string that you pass to printf, so that you don’t forget the quotes when you need them.

See Also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.161.222