大部分功能強大的文本編輯器都提供重新格式化段落的命令;供用戶切分段落,使文本行數(shù)不要超出我們看到的屏幕范圍。這樣我們就引入了 fmt 命令,雖然一些 fmt 的實現(xiàn)有較多的選項可用,但其實只用:-s 僅切割較長的行,但不會將短行結合成較長的行,而 -w n 則設置輸出行寬度為 n 個字符 (默認通常是 75 個)。
fmt 命令的語法:
fmt [option] [file-list]
fmt 通過將所有非空白的長度設置為幾乎相同,來進行簡單的文本格式化。
-s 截斷長行,但不合并-t 除每個段落的第 1 行外都縮進-u 改變格式化,使字之間出現(xiàn)一個空格,句子之間出現(xiàn)兩個空格-w n 將輸出的行寬改為 n 個字符。不帶該選項時,fmt 輸出的行寬度為 75 個字符例如,我有一個文件 demo,內(nèi)容為:
A long time ago, there was a huge apple tree.A little boy loved to come and play around it every day. He climbed to the tree top, ate the apples, took a nap under the shadow… He loved the tree and the tree loved to play with him.
使用命令 fmt -s demo,輸出為:
A long time ago, there was a huge apple tree.A little boy loved
to come and play around it every day. He climbed to the tree top, ate
the apples, took a nap under the shadow… He loved the tree and the
tree loved to play with him.
該命令的含義是節(jié)段 2 長行。
使用 fmt -t demo 命令的意思是說排除首行的縮進,結果為:
A long time ago, there was a huge apple tree. A little boy loved
to come and play around it every day. He climbed to the tree top,
ate the apples, took a nap under the shadow… He loved the tree and
the tree loved to play with him.
使用 fmt -u demo 命令的意思是說格式化單詞和句子的間隔。輸出為:
A long time ago, there was a huge apple tree. A little boy loved to come
and play around it every day. He climbed to the tree top, ate the apples,
took a nap under the shadow… He loved the tree and the tree loved to
play with him.
顯然 A little boy 前面的多個空格變成了兩個。
使用命令 fmt -w 40 demo 意思是說指定行的寬度,這里的行寬為 40 個字符。所以輸出為:
A long time ago, there was a huge
apple tree. A little boy
loved to come and play around it
every day. He climbed to the tree top,
ate the apples, took a nap under the
shadow… He loved the tree and the
tree loved to play with him.
僅作切割的選項: -s,在你想將長的行繞回,短的行保持不動時很好用,這么做也能使結果與原始版本間的差異達到最小,例如:
fmt -s -w 10 << EOF
one two three four five
six
seven
eight
輸出為:
one two
three
four five
six
seven
eight
fmt 的小案例:
下面以拼音字典為例:
字典文件:/usr/dict/words 或者 /usr/share/dict/words。
sed -n -e 9991,10010p /usr/share/dict/words | fmtsed -n -e 9991,10010p /usr/share/dict/words | fmt -w 30觀察上面兩行命令的輸出。
復習一下 sed 命令:
sed 是一個很好的文件處理工具,本身是一個管道命令,主要是以行為單位進行處理,可以將數(shù)據(jù)行進行替換、刪除、新增、選取等特定工作。假設我們有一個文件 demo
sed '1d' demo 刪除第一行
sed -n '1p' 顯示第一行
sed -n '/root/p' demo 查詢包括關鍵字 root 所在所有行
sed '1a hahaha' demo 第一行后增加字符串 hahaha
sed '1,3a hahaha' demo 第一行到第三行后增加字符串 hahaha
sed '1c hihihi' demo 第一行代替為 hihihi
sed '1,2c hihihi' demo 第一行和第二行替換為 hihihi
替換一行中的某部分
格式:sed 's/ 要替換的字符串 / 新的字符串 /g' (要替換的字符串可以用正則表達式),案例:
sed 's/root/hahaha/g' 替換 root 為 hahaha
sed 's/root//g' 刪除 root
sed -i '$a bye' ab #在文件 ab 中最后一行直接輸入 "bye"