是否有命令行工具可以将换行符插入长字符串?

Cor*_*ein 19 text-processing

给定一个需要以有限文本宽度显示的长字符串,*nix 中是否有命令行工具可以将单行字符串转换为每行不超过给定文本宽度的多行字符串?

例如,给定以下字符串

$ MYSTRING="Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world."
Run Code Online (Sandbox Code Playgroud)

我想格式有点像这样:

$ echo $MYSTRING | special-format-command --width=30
Call me Ishmael. Some years ag
o - never mind how long precis
ely - having little or no mone
y in my purse, and nothing par
ticular to interest me on shor
e, I thought I would sail abou
t a little and see the watery 
part of the world.
Run Code Online (Sandbox Code Playgroud)

Chr*_*her 27

你可以试试这个fold命令:

echo "$MYSTRING" | fold -w 30
Run Code Online (Sandbox Code Playgroud)

  • 对于后代,还有`fmt`。`fold` 和 `fmt` 之间的区别在于 `fold` 会以固定的宽度换行,甚至拆分单词并且可能以空格开始行。虽然 `fmt` 将在宽度附近或下方换行,但不会拆分单词,行不会以空格开头,并且可以连接短行。 (5认同)
  • 当使用 `-s` 选项时,`fold` 似乎具有与 `fmt` 相似的行为。 (5认同)
  • +1,但也许更好地写成`echo $MYSTRING | fold -w 30`,因为 `-30` 语法没有出现在 [fold 手册页](http://linux.die.net/man/1/fold) 中? (2认同)

Chr*_*own 6

这是一种使用方法sed

sed 's/.\{30\}/&\
/g'
Run Code Online (Sandbox Code Playgroud)


cas*_*cas 6

的全部目的fmt(GNU的coreutils,并IIRC其他版本的一部分被列入非GNU * nixes,因此几乎可以肯定已经安装)是重新格式化段落。

但是,有一个更好的工具叫做par(用于段落重新格式化)。它可以做所有fmt可以做的事情,但有更多的选项来控制确切的输出格式。

许多非常好的事情之一par是它在处理电子邮件中的引用(甚至是多级引用)方面非常聪明 - 非常有用......我设置了我的 .vimrc 以便按 F5 通过标准发送当前段落。

如果它不是为你的发行版打包的(它是为 debian 和衍生品,也可能是其他的),可以在http://www.nicemice.net/par/找到 par /