Format and print data From the phrase “print formatted”
printf "format" arguments
[me@linuxbox ~]$ printf "I formatted the string: %s\n" foo
I formatted the string: foo
[me@linuxbox ~]$ printf "I formatted '%s' as a string.\n" foo
I formatted 'foo' as a string.
Specifier | Description |
---|---|
d | Format a number as a signed decimal integer. |
f | Format and output a floating-point number |
o | Format an integer as an octal number |
s | Format a string |
x | Format an integer as a hexadecimal number using lowercase |
a to f where needed. | |
X | Same as X but use uppercase letters. |
% | Print a literal % symbol (i.e., specify %%) |
Common printf Data type Specifiers
[me@linuxbox ~]$ printf "%d, %f, %o, %s, %x, %X\n" 380 380 380 380 380 380
380, 380.000000, 574, 380, 17c, 17C
Optional components may be added to conversion specifier:
%[flags][width][.precision]conversion_specification
Component | Description |
---|---|
flags | There are five different flags: |
# : Use the “alternate format” for output. This varies by | |
data type. For o (octal number) conversion, the output | |
is prefixed with 0. For x and X (Hexadecimal number) | |
conversions, the output is prefixed with 0x or 0X. | |
0 : Pad the output with zeros. Fill field with | |
leading zeros. | |
- : Left-align the output. Default is right-aligned. | |
' ' : Produce a leading space for positive numbers. | |
+ : Sign positive numbers. Default, only sign | |
negative numbers. | |
width | A number specifying the minimum field width. |
.precision | For floating-point numbers, specify the number of digits |
of precision to be output after the decimal point. For | |
string conversion, precision specifies the number of | |
characters to output. |
printf Conversion Specification Components
[me@linuxbox ~]$ printf "Line: %05d %15.3f Result: %+15d\n" 1071 3.14156295
32589
Line: 01071 3.142 Result: +32589