如何以特定的列大小换行文本?

cwd*_*cwd 177 text-processing

我知道我可以使用类似cat test.txt | pr -w 80将行换行至 80 个字符宽的方法,但这会在打印行的顶部和底部放置大量空间,并且在某些系统上无法正常工作

强制以特定宽度换行的长行文本文件的最佳方法是什么?

如果你能防止打断的话,加分。

小智 224

你正在寻找

fold -w 80 -s text.txt
Run Code Online (Sandbox Code Playgroud)
  • -w 告诉文本的宽度,其中 80 是标准的。
  • -s 告诉在空格处打断,而不是在单词中打断。

这是标准方式,但还有其他系统需要“-c”而不是“-w”。

  • 请注意,`fold` 会破坏 url,而 `fmt` 不会。 (4认同)
  • 附带说明一下,为了很好地格式化电子邮件以进行纯文本回复,我使用:`fold -s -w 80 email.txt | sed 's/^.*$/> &/'` (3认同)
  • @MarcelloRomani,您不应该使用 78 的宽度,因为您要添加两个字符吗? (2认同)
  • 有没有像 `fold` 这样的东西可以让你指定一个字符串来换行? (2认同)
  • 在 mingw 中工作得很好,但它在某些行的末尾留下了尾随空白。有没有一种巧妙的方法来解决这个问题? (2认同)

小智 62

另外fold,看看fmt。fmt尝试智能地选择换行符以使文本看起来更好。它不会打破长词,而是仅由空格包裹。它还会连接相邻的行,这对散文有益,但对日志文件或其他格式化文本不利。

  • 与 fold 相比,我特别喜欢 fmt -t (4认同)

use*_*246 32

$ cat shxp.txt

O, they have lived long on the alms-basket of words, I marvel thy
master hath not eaten thee for a word; for thou art not so long by the
head as honorificabilitudinitatibus: thou art easier swallowed than a
flap-dragon.
Run Code Online (Sandbox Code Playgroud)

1?) 保证固定的线宽和断字:

fold -w 20 <shxp.txt

O, they have lived l
ong on the alms-bask
et of words, I marve
l thy master hath no
t eaten thee for a w
ord; for thou art no
t so long by the hea
d as honorificabilit
udinitatibus: thou a
rt easier swallowed
than a flap-dragon.
Run Code Online (Sandbox Code Playgroud)

2?) 保证固定的线宽和非凡的断字。一个单词只有在它太大而不能放在一行中时才会被破坏:

fold -sw 20 <shxp.txt

O, they have lived
long on the
alms-basket of
words, I marvel thy
master hath not
eaten thee for a
word; for thou art
not so long by the
head as
honorificabilitudini
tatibus: thou art
easier swallowed
than a flap-dragon.
Run Code Online (Sandbox Code Playgroud)

3?)有希望的固定线宽没有任何断字。如果单词太大而不能放在一行中,它仍然保持原样,所以最后一些行的大小可能比您需要的要大:

fmt -w 20 <shxp.txt

O, they have
lived long on the
alms-basket of
words, I marvel
thy master hath
not eaten thee
for a word; for
thou art not so
long by the head as
honorificabilitudinitatibus:
thou art easier
swallowed than
a flap-dragon.
Run Code Online (Sandbox Code Playgroud)

  • 被低估的答案。在大多数系统上可用。好一个。 (2认同)
  • 我真的很高兴看到具有不同选项的真实文本示例。我一直在尝试编写`wrap`的Python版本,但对长字处理不满意。对于长于指定的单词使用“wrap”和“fwt”选项非常好。 (2认同)

don*_*sti 13

另一个(鲜为人知的)工具可以满足您的需求,它wrap来自 GNU Talkfilters:

wrap -w 80 < textfile
Run Code Online (Sandbox Code Playgroud)

还有(题外话):

但这会在打印线的顶部和底部放置很多空间

-t调用时添加pr以省略标题/预告片:

   -t, --omit-header
          omit page headers and trailers
Run Code Online (Sandbox Code Playgroud)


sen*_*nfo 8

有关更多格式选项,请查看par-- http://www.nicemice.net/par/

  • 目前该网站已关闭,有 Internet Archive 和 Google 的缓存,但这仍然说明了为什么发布更多链接很重要,您至少可以发布官方文档中的示例。 (3认同)