Shell printf 命令

格式化占位符、宽度与对齐、数字格式,以及和 C 语言 printf 的对应关系。

Beginner
Key Pointsprintf 不会自动加换行,格式串里要自己写 \n;参数多于占位符时会重复套用格式串。

基本格式

Bash
printf "hello %s\n" "world"
printf "%d + %d = %d\n" 2 3 5
printf "%.2f\n" 3.14159
printf "%x %X\n" 255 255
Output
hello world
2 + 3 = 5
3.14
ff FF

占位符

SpecMeaning
%sString
%dInteger
%fFloat (default 6 decimals)
%.2fFloat with 2 decimals
%x / %XHex lower / upper
%cFirst character
%%Literal percent

宽度与对齐

Bash
printf "%-10s|%10s|\n" "name" "score"
printf "%-10s|%10d|\n" "alice" 90
printf "%-10s|%10d|\n" "bob" 8
Output
name      |     score|
alice     |        90|
bob       |         8|

- left-aligns, the number is the minimum width, padded with spaces. Far more reliable than padding with echo.

参数多于占位符

Bash
printf "%s\n" one two three
printf "[%s] " a b c; echo
Output
one
two
three
[a] [b] [c] 

数字格式

Bash
printf "%05d\n" 42
printf "%+d %+d\n" 5 -5
printf "%.1f%%\n" 99.55
Output
00042
+5 -5
99.6%
% is special in the format string; write %% for a literal percent. Forgetting it garbles generated nginx or cron files.

Friends & Partners