在日常使用 Linux 系统,尤其是 Debian 及其衍生发行版(如 Ubuntu)时,我们经常需要对纯文本进行格式化处理。比如写文档、整理日志、排版代码注释等。这时,fmt 命令就派上用场了!
fmt 是一个轻量级但功能强大的文本格式化工具,它能自动将一段杂乱无章的文本重新排版为指定宽度的整齐段落,非常适合处理英文或中英文混合的普通文本。
fmt 是 GNU coreutils 软件包的一部分,在大多数 Debian 系统中默认已安装。它的核心功能是:将输入的文本按指定列宽重新排列成整齐的段落,同时尽量保持单词完整、不被截断。
fmt 的基本用法非常简单:
fmt [选项] [文件...] 如果不指定文件,fmt 会从标准输入(stdin)读取内容。
-w N 或 --width=N:设置输出行的最大宽度为 N 列(默认是 75 列)。-s 或 --split-only:只拆分过长的行,不合并短行(适合处理已排版好的列表或代码注释)。-u 或 --uniform-spacing:统一空格格式(句子间用两个空格,单词间一个空格)。-p PREFIX:保留每行开头的指定前缀(常用于注释块,如 // 或 #)。假设你有一个名为 article.txt 的文件,内容是一段没有换行的长文本:
This is a very long sentence that has no line breaks and will be difficult to read if displayed in a terminal without proper formatting. We can use the fmt command to make it look neat and readable. 运行以下命令:
fmt -w 60 article.txt 输出结果将被限制在每行最多 60 个字符,并自动换行:
This is a very long sentence that has no line breaks andwill be difficult to read if displayed in a terminalwithout proper formatting. We can use the fmt command tomake it look neat and readable. 如果你有一段 C 语言注释:
// This function calculates the factorial of a given number n.// It uses recursion and assumes that n is a non-negative integer. 使用 -p 选项保留 // 前缀:
fmt -w 50 -p "//" comments.txt 输出将保持注释符号对齐,同时格式化文字内容。
直接在终端运行 fmt,然后输入多行文本,按 Ctrl+D 结束输入:
$ fmt -w 40Hello world this is a test of the fmt commandin Debian Linux system.[按 Ctrl+D]Hello world this is atest of the fmt commandin Debian Linux system. 相比其他文本处理工具(如 fold 或手动编辑),fmt 的优势在于:
fmt 主要针对英文设计,对中文支持有限(因中文无空格分词)。建议中英文混排时谨慎使用。cat file.txt | fmt -w 70。sudo apt install coreutils(通常已预装)。通过本教程,相信你已经掌握了 Debian fmt命令 的基本用法。无论是写技术文档、整理笔记,还是自动化脚本中的文本预处理,fmt 都是一个值得信赖的帮手。快在你的终端里试试吧!
记住这些关键词:Debian fmt命令、文本格式化工具、Linux命令行格式化、fmt命令教程,它们将帮助你在未来快速检索相关知识。
本文由主机测评网于2025-12-21发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://vpshk.cn/20251210726.html