linux awk 中 printf 使用方法:
printf()函数是格式化输出函数, 一般用于向标准输出设备按规定格式输出信息。
printf()函数的调用格式为:
printf("<格式化字符串>", <参量表>);
其中格式化字符串包括两部分内容: 一部分是正常字符, 这些字符将按原样输出; 另一部分是格式化规定字符, 以"%"开始, 后跟一个或几个规定字符,用来确定输出内容格式。
参量表是需要输出的一系列参数, 其个数必须与格式化字符串所说明的输出参数个数一样多, 各参数之间用","分开, 且顺序一一对应, 否则将会出现意想不到的错误。
%d 十进制有符号整数
%u 十进制无符号整数
%f 浮点数
%s 字符串
%c 单个字符
%p 指针的值
%e 指数形式的浮点数
%x, %X 无符号以十六进制表示的整数
%0 无符号以八进制表示的整数
%g 自动选择合适的表示法
\n 换行
\f 清屏并换页
\r 回车
\t Tab符
\xhh 表示一个ASCII码用16进表示,其中hh是1到2个16进制数
[root@centos7 ~]# printf "%-10s %-10s %-4s %-4s \n" 姓名 性别 年龄 体重 苹果 男 18 60 香蕉 男 18 80
姓名 性别 年龄 体重
苹果 男 18 60
香蕉 男 18 80
[root@centos7 ~]#
#"-"表示左对齐, "10 10 4 4" 表示占的字符位数, 不够不空格
[root@centos7 ~]# printf "%s %s\n" 1 2 3 4
1 2
3 4
[root@centos7 ~]#
[root@centos7 ~]# printf " (%s) " 1 2 3 4;echo ""
(1) (2) (3) (4)
[root@centos7 ~]#
[root@centos7 ~]# printf "%-6s %-6s %-6s\n" ID Name Number
ID Name Number
[root@centos7 ~]#
[root@centos7 ~]# cat file
aa bb cc
dd ee ff
gg hh ll
[root@centos7 ~]# cat file |xargs printf "%-2s\n"
aa
bb
cc
dd
ee
ff
gg
hh
ll
[root@centos7 ~]#
[root@centos7 ~]# cat file
aa bb cc
dd ee ff
gg hh ll
[root@centos7 ~]# cat file |xargs printf "%-5s"
aa bb cc dd ee ff gg hh ll [root@centos7 ~]#
[root@centos7 ~]#
[root@localhost ~]# printf %s 1 2 3 4 5 6
123456[root@localhost ~]# printf %s %s %s 1 2 3 4 5 6
%s%s123456[root@localhost ~]# printf '%s %s %s' 1 2 3 4 5 6
1 2 34 5 6[root@localhost ~]# printf '%s\t%s\t%s\n' 1 2 3 4 5 6
1 2 3
4 5 6
[root@localhost ~]# printf '%s' $(cat student.txt)
1furongF852fengjF603cangF70[root@localhost ~]#
[root@localhost ~]# printf '%s\t%s\t%s\t%s\n' $(cat student.txt)
1 furong F 85
2 fengj F 60
3 cang F 70