格式化輸出-printf命令

格式化輸出命令

printf 和 echo命令類似,輸出

printf 是linux 的標準輸出命令

#printf   '輸出類型輸出格式' 輸出內容

輸出類型:

  • %ns:輸出字符串。n是數字,指輸出幾個字符
  • %ni:輸出整數。n是數字,指輸出幾個數字
  • %m.nf:輸出浮點數。m和n是數字,指輸出的整數位和小數位,如%8.2f代表共輸出8位數,其中2位小數,6位是整數

輸出格式

  • \a :輸出警告聲音
  • \b :輸出退格鍵,也就是backspace鍵
  • \f :清除屏幕
  • \n :換行
  • \r :回車,也即是enter鍵
  • \t :水平輸出退格鍵,也就是tab鍵
  • \v :垂直輸出退格鍵,也就是tab鍵

例如:

[root@localhost ~]# printf %8.2f 11111.34
11111.34[root@localhost ~]# printf %s 1 2 3 4 5 6
123456[root@localhost ~]# echo 1 2 3 4 5 6 
1 2 3 4 5 6
[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'  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\t %s\t %s\n'  1 2 3 4 5 6
1    2   3
4    5   6

文件中的內容:

[root@localhost home]# cat student.txt 
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   70

讀取文件中的內容:

[root@localhost home]# printf '%s' $(cat student.txt)
IDNamegenderMark1furongF882fengjieF603cangF70[root@localhost home]# 
[root@localhost home]# printf '%s\t%s\t%s\t%s\n' $(cat student.txt)
ID  Name    gender  Mark
1   furong  F   88
2   fengjie F   60
3   cang    F   70

注意:

在awk命令的輸出中支持print和printf命令

  • print:print會在每個輸出之後自動添加一個換行符(Linux默認沒有print命令)
  • printf:printf是標準格式輸出命令,並不會自動添加換行符,如果需要換行,需要手工添加換行符
發佈了81 篇原創文章 · 獲贊 19 · 訪問量 35萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章