1. 程式人生 > 實用技巧 >9,linux printf命令

9,linux printf命令

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