您当前的位置:首页 > 计算机 > 系统应用 > Linux

我所不知道的 printf 命令特性

时间:12-14来源:作者:点击数:

printf 有多个版本

除了 /usr/bin/printf 外,每个 shell 一般都会定义自己内置的 printf 命令。而且通过查看 man printf 你会看到这么一段说明:

NOTE: your shell may have its own version of printf, which usually supersedes
the version described here. Please refer to your shell's
documentation for details about the options it supports.

也就是说,我们通常使用的 printf 命令都是 shell 内置的 printf 命令。

格式字符串可以被复用

参数列表中的参数个数可以多于格式字符串中要求的参数个数,这种情况下格式字符串会被复用,例如下面这段程序

printf "%-20s: %4d\n" "string 1" 12 "string 2" 122
string 1:   12
string 2:  122

不足的参数列表将会用空字符串或0补足

若参数列表中的参数个数少于格式字符串中要求的参数个数,则会使用空字符串(格式对应字符串时)或 0(格式对应数字时)进行填充

printf "%s: %d\n" "string 1"
printf "%d: %s\n" "1"
string 1: 0
1: 

支持由参数指定的长度

使用 * 来标识长度,这种情况下表示长度由下一个参数决定

printf "%*s: %*d\n" -20 "a string" 4 12
a string            :   12

需要说明的是,若同时需要指明用0填充空白域和由参数指定长度,请保证 0 放在 * 之前:

printf "%*s: %0*d\n" -20 "a string" 4 12
a string            : 0012

bash 内置 printf 独特的 %(datefmt)T 占位符

bash 内置的 printf 支持占位符 %(datefmt)T,它的值是从纪元开始经过的秒钟数(可以通过 date +%s 里获取),其中 datefmt 的格式跟 strftime(3) 一样。

printf "%(%m-%d-%Y %H:%M:%S)T\n" -$(date +%s)
11-05-1920 04:41:16

当使用 %(datefmt)T 格式时,有两个特殊值需要注意:

1、-1 表示当前时间,同时也是缺少参数时的缺省值

printf "%(%m-%d-%Y %H:%M:%S)T\n"
printf "%(%m-%d-%Y %H:%M:%S)T\n" -1
02-27-2019 11:22:20
02-27-2019 11:22:20

2、-2 表示 shell 启动的时间

sleep 5
printf "%(%m-%d-%Y %H:%M:%S)T\n"
printf "%(%m-%d-%Y %H:%M:%S)T\n" -2
02-27-2019 11:23:04
02-27-2019 11:22:59
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐