linux 中printf函数

 

001、输出字符串

[root@PC1 test01]# printf "abcd\n"
abcd
[root@PC1 test01]# printf "%s\n" "abcd"       ## 输出字符串
abcd

 

002、指定宽度

[root@PC1 test01]# printf "%s\n" "abcd"
abcd
[root@PC1 test01]# printf "%10s\n" "abcd"      ## 指定宽度为10, 默认右侧对齐
      abcd
[root@PC1 test01]# printf "%-10s\n" "abcd"     ## 指定宽度为10, 左侧对齐
abcd

 

003、输出整数值

[root@PC1 test01]# printf "%d\n" "1234"         ## 输出数值
1234
[root@PC1 test01]# printf "%10d\n" "1234"       ## 指定宽度为10
      1234
[root@PC1 test01]# printf "%010d\n" "1234"      ## 多余的位数用0来填充
0000001234

 

004、输出浮点数

[root@PC1 test01]# printf "%f\n" "1234"          ## 输出浮点数
1234.000000
[root@PC1 test01]# printf "%.2f\n" "1234"        ## 指定浮点的位数
1234.00
[root@PC1 test01]# printf "%10.2f\n" "1234"      ## 指定宽度
   1234.00
[root@PC1 test01]# printf "%010.2f\n" "1234"     ## 多余的宽度用0来填充
0001234.00

 

005、科学计数法

[root@PC1 test01]# printf "%e\n" "1234"        ## 科学计数法, 默认是6位小数
1.234000e+03
[root@PC1 test01]# printf "%E\n" "1234"
1.234000E+03
[root@PC1 test01]# printf "%.2e\n" "1234"      ## 指定小数位数
1.23e+03

 

006、用16进制来表示

[root@PC1 test01]# printf "%x\n" 15    ## 用16进制表示, 10 - 15 用a-f表示
f
[root@PC1 test01]# printf "%x\n" 16    
10
[root@PC1 test01]# printf "%x\n" 17    ## 用16进制表示
11

 

007、用八进制表示

[root@PC1 test01]# printf "%o\n" 7
7
[root@PC1 test01]# printf "%o\n" 8       ## 用8进制数来表示
10
[root@PC1 test01]# printf "%o\n" 9
11

 

008、转义后的双引号和单引号

[root@PC1 test01]# printf "abcd\n"
abcd
[root@PC1 test01]# printf "ab\"cd\n"     ## 转义后的双引号
ab"cd
[root@PC1 test01]# printf "ab\'cd\n"     ## 转义后的单引号
ab'cd

 

009、\b表示退格符

[root@PC1 test01]# printf "abcd\n"
abcd
[root@PC1 test01]# printf "ab\bcd\n"    ## \b表示退格符
acd

 

010、\r表示回车符

[root@PC1 test01]# printf "abcd\n"
abcd
[root@PC1 test01]# printf "ab\rcd\n"     ## \r?
cd

 

011、\t 水平制表符, \v表示垂直制表符

[root@PC1 test01]# printf "abcd\n"
abcd
[root@PC1 test01]# printf "ab\tcd\n"       ## 水平制表符
ab      cd
[root@PC1 test01]# printf "ab\vcd\n"       ## 垂直制表符
ab
  cd

 

012、输出单个%

[root@PC1 test01]# printf "abcd\n"
abcd
[root@PC1 test01]# printf "ab%cd\n"
abd
[root@PC1 test01]# printf "ab%%cd\n"          ## 输出单个%号
ab%cd

 

013、实例1

[root@PC1 test01]# printf "Decimal: %d\nHex: %x\nOctal: %o\n" 100 100 100   ## 十进制、16进制、8进制
Decimal: 100
Hex: 64
Octal: 144

 

014、实例2

[root@PC1 test01]#  printf "%s \t %s \t %s\n" "姓名" "性别" "年龄" "小明" "" "18" "小 红" "" "19" "小蓝" "" "18"
姓名     性别    年龄
小明     男      18
小红     女      19
小蓝     男      18

 

参考:http://e.betheme.net/article/show-82485.html?action=onClick

 

posted @ 2023-06-22 18:03  小鲨鱼2018  阅读(400)  评论(0编辑  收藏  举报