printf 指令模仿 C 程式庫(library)裡的 printf() 程式。
标準所定義,是以使用printf的腳本比使用echo移植性好。
printf 使用引用文本或空格分隔的參數,外面可以在printf中使用格式化字元串,還可以制定字元串的寬度、左右對齊方式等。預設printf不會像 echo 自動添加換行符,我們可以手動添加 \n。
printf 指令的文法:
參數說明:
format-string: 為格式控制字元串
arguments: 為參數清單。
執行個體如下:
1
2
3
4
5
<code>$ </code><code>echo</code> <code>"Hello, Shell"</code>
<code>Hello, Shell</code>
<code>$ </code><code>printf</code> <code>"Hello, Shell\n"</code>
<code>$</code>
接下來,我來用一個腳本來展現printf的強大功能:
6
<code>#!/bin/bash</code>
<code> </code>
<code>printf</code> <code>"%-10s %-8s %-4s\n"</code> <code>姓名 性别 體重kg </code>
<code>printf</code> <code>"%-10s %-8s %-4.2f\n"</code> <code>郭靖 男 66.1234 </code>
<code>printf</code> <code>"%-10s %-8s %-4.2f\n"</code> <code>楊過 男 48.6543 </code>
<code>printf</code> <code>"%-10s %-8s %-4.2f\n"</code> <code>郭芙 女 47.9876</code>
執行腳本,輸出結果如下所示:
%s %c %d %f都是格式替代符
%-10s 指一個寬度為10個字元(-表示左對齊,沒有則表示右對齊),任何字元都會被顯示在10個字元寬的字元内,如果不足則自動以空格填充,超過也會将内容全部顯示出來。
%-4.2f 指格式化為小數,其中.2指保留2位小數。
更多執行個體:
7
8
9
10
11
12
13
14
<code># format-string為雙引号</code>
<code>printf</code> <code>"%d %s\n"</code> <code>1 </code><code>"abc"</code>
<code># 單引号與雙引号效果一樣 </code>
<code>printf</code> <code>'%d %s\n'</code> <code>1 </code><code>"abc"</code>
<code># 沒有引号也可以輸出</code>
<code>printf</code> <code>%s abcdef</code>
<code># 格式隻指定了一個參數,但多出的參數仍然會按照該格式輸出,format-string 被重用</code>
<code>printf</code> <code>%s abc def</code>
<code>printf</code> <code>"%s\n"</code> <code>abc def</code>
<code>printf</code> <code>"%s %s %s\n"</code> <code>a b c d e f g h i j</code>
<code># 如果沒有 arguments,那麼 %s 用NULL代替,%d 用 0 代替</code>
<code>printf</code> <code>"%s and %d \n"</code>
序列
說明
\a
警告字元,通常為ASCII的BEL字元
\b
後退
\c
抑制(不顯示)輸出結果中任何結尾的換行字元(隻在%b格式訓示符控制下的參數字元串中有效),而且,任何留在參數裡的字元、任何接下來的參數以及任何留在格式字元串中的字元,都被忽略
\f
換頁(formfeed)
\n
換行
\r
回車(Carriage return)
\t
水準制表符
\v
垂直制表符
\\
一個字面上的反斜杠字元
\ddd
表示1到3位數八進制值的字元。僅在格式字元串中有效
\0ddd
表示1到3位的八進制值字元
<code>$ </code><code>printf</code> <code>"a string, no processing:<%s>\n"</code> <code>"A\nB"</code>
<code>a string, no processing:<A\nB></code>
<code>$ </code><code>printf</code> <code>"a string, no processing:<%b>\n"</code> <code>"A\nB"</code>
<code>a string, no processing:<A</code>
<code>B></code>
<code>$ </code><code>printf</code> <code>"www.runoob.com \a"</code>
<code>www.runoob.com $ </code><code>#不換行</code>
本文轉自 獨孤環宇 51CTO部落格,原文連結:http://blog.51cto.com/snowtiger/1941352