Linux printf 命令

printf 命令用来格式化输出,用法如下:

[keysystem@localhost ~]$ printf "%s
" 1 2 3 4
1
2
3
4
[keysystem@localhost ~]$ printf "%f
" 1 2 3 4
1.000000
2.000000
3.000000
4.000000
[keysystem@localhost ~]$ printf "%.2f
" 1 2 3 4
1.00
2.00
3.00
4.00
[keysystem@localhost ~]$ printf " (%s) " 1 2 3 4;echo ""
 (1)  (2)  (3)  (4) 
[keysystem@localhost ~]$ printf "%s %s
" 1 2 3 4
1 2
3 4
[keysystem@localhost ~]$ printf "%s %s %s
" 1 2 3 4
1 2 3
4[keysystem@localhost ~]$ printf "%-10s %-10s %-4s %-4s 
" 姓名 性别 年龄 体重 苹果 男 18 60 香蕉 男 18 80
姓名     性别     年龄 体重 
苹果     男        18   60     # "-"表示左对齐, "10 10 4 4" 表示占的字符位数, 不够的用空格替代
香蕉     男        18   80
[keysystem@localhost ~]$ printf "%X " 13 # 10进制转16进制 D [keysystem@localhost ~]$ printf "%d" 0xB # 16进制转10进制 11

常用的格式替换符:

%s    # 字符串
%f    # 浮点格式
%c    # ASCII字符,即显示对应参数的第一个字符
%d    # 十进制整数
%o    # 八进制值
%u    # 不带正负号的十进制值
%x    # 十六进制值(a-f)
%X    # 十六进制值(A-F)
%%    # 表示%本身

常用的转义字符:

a    # 用于响铃,发出声音的响铃哦
    # 用于退格,参考:https://blog.csdn.net/lucosax/article/details/34963593
c    # 使用该转义符后,c 后面的字符不再输出
e    # 用于控制字体和背景颜色
f    # 换行,且光标停在换行后原来的地方

    # 换行符

    # 用于把光标移到行首,相当于把 
 前面的字符删除,只输出 
 后面的字符
	    # 制表符,相当于键盘上的Tab键
v    # 垂直制表符

    

原文地址:https://www.cnblogs.com/pzk7788/p/10450967.html