Linux 中的 fmt 命令及示例
LINUX 中的 fmt命令实际上用作简化和优化文本文件的格式化程序。文本文件的格式化也可以手动完成,但是当涉及到大文本文件时,它真的很耗时,这就是fmt 的用武之地。
fmt重新格式化指定文件中的每个段落,写入标准输出。这是fmt命令的语法:
// syntax of fmt command
$fmt [-WIDTH] [OPTION]... [FILE]...
其中, -WIDTH是 –width=DIGITS的缩写, OPTION是指与fmt命令兼容的选项,FILE是指文件名。
如果未指定 FILE,或者 FILE 是破折号(“-”),则fmt从标准输入读取。
使用 fmt 命令
默认情况下 fmt不使用任何选项将给定文件中存在的所有单词格式化为一行。
$ cat kt.txt
hello
everyone.
Have
a
nice
day.
/* fmt by default puts all words
in a single line and prints on
stdout. */
$fmt kt.txt
hello everyone. Have a nice day.
要保存或写入格式化输出,您可以将 fmt 用作:
/* Here the formatted output gets
written in dv.txt */
$fmt kt.txt > dv.txt
fmt 命令的选项
- -w, – -width=WIDTH 选项:默认情况下,fmt 命令在输出中产生的最大宽度为 75,但在-w选项的帮助下可以更改它,它只需要您要指定的宽度的数值.
$cat kt.txt hello everyone. Have a nice day. /* the width gets reduced to 10 with -e option */ $fmt -w 10 kt.txt hello ever yone. Have a nice day.
- -t, – -tagged-paragraph 选项:可能需要突出显示文本文件中的第一行,这可以通过使第一行的缩进与可以使用-t命令完成的其他行不同来完成。
$cat kt.txt hello everyone. Have a nice and prosperous day. /*-t makes the indentation of first line different from others */ $fmt -t kt.txt hello everyone. Have a nice and prosperous day.
- -s 选项:此选项拆分长行,但不重新填充它们。
$cat kt.txt Love is patient, love is kind. It does not envy, it does not boast, it is not proud. It is not rude, it is not self-seeking, it is not easily angered, it keeps no record of wrongs. Love does not delight in evil but rejoices with the truth. It always protects, always trusts, always hopes, always perseveres. Love never fails. /* long lines get splited with -s option */ $fmt -s kt.txt Love is patient, love is kind. It does not envy, it does not boast, it is not proud. It is not rude, it is not self-seeking, it is not easily angered, it keeps no record of wrongs. Love does not delight in evil but rejoices with the truth. It always protects, always trusts, always hopes, always perseveres. Love never fails.
- -u, – -uniform-spacing 选项:此选项使用单词之间的一个空格和句子后的两个空格进行格式化。
$cat kt.txt Love is patient, love is kind. It does not envy, it does not boast, it is not proud. /* Spaces are uniformed with -u option */ $fmt -u kt.txt Love is patient, love is kind. It does not envy, it does not boast, it is not proud.
- -c, – -crown-margin 选项:此选项保留前两行的缩进。
- -p, – -prefix=STRING 选项:此选项将 STRING 作为参数并仅重新格式化以 STRING 开头的行,将前缀重新附加到重新格式化的行。
- -g, – -goal=WIDTH 选项:此选项指的是目标宽度,即默认宽度的 93%。
- – -help 选项:显示帮助信息并退出。
- – -version 选项:显示版本信息并退出。
fmt 命令的应用:
- fmt允许您使用诸如 -u 之类的选项轻松格式化大文本文件,如果手动完成,这可能是一项非常困难的任务。
- fmt还允许您在 -w 选项的帮助下更改默认宽度。
- 这是在格式化文件时节省时间的好方法。