我是如何使用 Linux fmt 命令來格式化文本
當(dāng)我為項(xiàng)目編寫文檔時(shí),我經(jīng)常以純文本的形式編寫自述文件和安裝說明。我不需要使用 HTML 或者 Markdown 之類的標(biāo)記語言來描述項(xiàng)目的功能或如何編譯它。但是維護(hù)這樣的文檔可能會(huì)很痛苦。
如果我需要更新我的 Readme 文件中的一個(gè)句子的中間位置,我需要重新格式化文本,以避免在我的其它文本中間出現(xiàn)一個(gè)很長或很短的行,而其它的行的格式是整整齊齊的 75 列。一些編輯器包含可以自動(dòng)重新格式化文本以填充段落的功能,但并非所有的編輯器都這樣做。這就是 Linux fmt 命令的用武之地。
使用 Linux fmt 命令格式化文本
fmt 命令是一個(gè)簡單的文本格式化程序;它收集單詞并填充段落,但不應(yīng)用任何其它文本樣式,例如斜體或粗體。這一切都是純文本。使用 fmt 命令,你可以快速調(diào)整文本,使其更易于閱讀。讓我們從這個(gè)熟悉的示例文本開始:
$ cat trek.txt
Space: the final
frontier. These are the voyages
of the starship Enterprise. Its
continuing mission: to explore
strange new worlds. To
seek out new life and new
civilizations. To boldly go
where no one has gone before!
在這個(gè)實(shí)例文件中,每行都有不同的長度,并且它們以一種奇怪的方式換行。如果你對(duì)純文本文件進(jìn)行大量更改,你可以會(huì)遇到類似的奇怪的換行。要重新格式化此文本,你可以使用 fmt 命令將段落的行填充為統(tǒng)一長度:
$ fmt trek.txt
Space: the final frontier. These are the voyages of the starship
Enterprise. Its continuing mission: to explore strange new worlds. To
seek out new life and new civilizations. To boldly go where no one has
gone before!
默認(rèn)情況下,fmt 會(huì)將文本格式化為 75 的列寬大小,但你可以使用 -w 或 --width 選項(xiàng)進(jìn)行更改:
$ fmt -w 60 trek.txt
Space: the final frontier. These are the voyages of
the starship Enterprise. Its continuing mission: to
explore strange new worlds. To seek out new life and new
civilizations. To boldly go where no one has gone before!
使用 Linux fmt 命令格式化電子郵件回復(fù)
我加入了一個(gè)郵件列表,這里更喜歡純文本電子郵件,這使得在列表服務(wù)器上歸檔電子郵件變得更加容易。但現(xiàn)實(shí)是并非每個(gè)人都以純文本形式發(fā)送電子郵件。有時(shí)候,當(dāng)我以純文本形式回復(fù)這些電子郵件時(shí),我的電子郵件客戶端會(huì)將整個(gè)段落放在一行中。這使得在電子郵件中“引用”回復(fù)變得困難。
這是一個(gè)簡單的例子。當(dāng)我以純文本形式回復(fù)電子郵件時(shí),我的電子郵件客戶端通過在每行前添加 > 字符來“引用”對(duì)方的電子郵件。對(duì)于一條短消息,可能如下所示:
> I like the idea of the interim development builds.
沒有正確“換行”的長行將無法在我的純文本電子郵件回復(fù)中正確顯示,因?yàn)樗皇乔懊鎺в?nbsp;> 字符的長行,如下所示:
> I like the idea of the interim development builds. This should be a great way to test new changes that everyone can experiment with.
為了解決這個(gè)問題,我打開了一個(gè)終端并將引用的文本復(fù)制并粘貼到一個(gè)新文件中。然后我使用 -p 或 --prefix 選項(xiàng)來告訴 fmt 在每一行之前使用什么字符作為“前綴”。
$ cat > email.txt
> I like the idea of the interim development builds. This should be a great way to test new changes that everyone can experiment with.
^D
$ fmt -p '>' email.txt
> I like the idea of the interim development builds. This should be a
> great way to test new changes that everyone can experiment with.
fmt 命令是一個(gè)非常簡單的文本格式化程序,但它可以做很多有用的事情,可以幫助以純文本形式編寫和更新文檔。要了解其它選項(xiàng),例如 -c 或 --crown-margin 以匹配段落前兩行縮進(jìn),例如項(xiàng)目列表。還可以嘗試使用 -t 或者 --tagged-paragraph 來保留段落中第一行的縮進(jìn),就像縮進(jìn)的段落一樣。-u 或 --uniform-spacing 選項(xiàng)在單詞之間使用一個(gè)空格,在句子之間使用兩個(gè)空格。