我是如何使用 Linux fmt 命令來格式化文本
當我為項目編寫文檔時,我經常以純文本的形式編寫自述文件和安裝說明。我不需要使用 HTML 或者 Markdown 之類的標記語言來描述項目的功能或如何編譯它。但是維護這樣的文檔可能會很痛苦。
如果我需要更新我的 Readme 文件中的一個句子的中間位置,我需要重新格式化文本,以避免在我的其它文本中間出現一個很長或很短的行,而其它的行的格式是整整齊齊的 75 列。一些編輯器包含可以自動重新格式化文本以填充段落的功能,但并非所有的編輯器都這樣做。這就是 Linux fmt 命令的用武之地。
使用 Linux fmt 命令格式化文本
fmt 命令是一個簡單的文本格式化程序;它收集單詞并填充段落,但不應用任何其它文本樣式,例如斜體或粗體。這一切都是純文本。使用 fmt 命令,你可以快速調整文本,使其更易于閱讀。讓我們從這個熟悉的示例文本開始:
$ 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!
在這個實例文件中,每行都有不同的長度,并且它們以一種奇怪的方式換行。如果你對純文本文件進行大量更改,你可以會遇到類似的奇怪的換行。要重新格式化此文本,你可以使用 fmt 命令將段落的行填充為統一長度:
$ 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!
默認情況下,fmt 會將文本格式化為 75 的列寬大小,但你可以使用 -w 或 --width 選項進行更改:
$ 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 命令格式化電子郵件回復
我加入了一個郵件列表,這里更喜歡純文本電子郵件,這使得在列表服務器上歸檔電子郵件變得更加容易。但現實是并非每個人都以純文本形式發送電子郵件。有時候,當我以純文本形式回復這些電子郵件時,我的電子郵件客戶端會將整個段落放在一行中。這使得在電子郵件中“引用”回復變得困難。
這是一個簡單的例子。當我以純文本形式回復電子郵件時,我的電子郵件客戶端通過在每行前添加 > 字符來“引用”對方的電子郵件。對于一條短消息,可能如下所示:
> I like the idea of the interim development builds.
沒有正確“換行”的長行將無法在我的純文本電子郵件回復中正確顯示,因為它只是前面帶有 > 字符的長行,如下所示:
> I like the idea of the interim development builds. This should be a great way to test new changes that everyone can experiment with.
為了解決這個問題,我打開了一個終端并將引用的文本復制并粘貼到一個新文件中。然后我使用 -p 或 --prefix 選項來告訴 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 命令是一個非常簡單的文本格式化程序,但它可以做很多有用的事情,可以幫助以純文本形式編寫和更新文檔。要了解其它選項,例如 -c 或 --crown-margin 以匹配段落前兩行縮進,例如項目列表。還可以嘗試使用 -t 或者 --tagged-paragraph 來保留段落中第一行的縮進,就像縮進的段落一樣。-u 或 --uniform-spacing 選項在單詞之間使用一個空格,在句子之間使用兩個空格。