如何将字符串分成 N 个 80 个字符的行?

如何将字符串分成 N 个 80 个字符的行?

我想在脚本开始时显示一条欢迎信息:

echo "Running $0 $@"

$@可能会很长。我怎样才能将此行分成多行,每行最多 80 个字符?

答案1

使用fold

echo "Running $0 $@" | fold -sw 80

-s按空格换行。 -w 80将宽度设置为 80 列。

答案2

当然fold是最好的选择,但您也可以使用grep或来实现这一点sed

echo "Running $0 $@" | grep -o '.\{80\}[^ ]* '
#or
echo "Running $0 $@" | sed -E 's/(.{80}[^ ]*) /\1\n/g'

请注意,这将在 80 个字符 + 1 个单词处中断,因此可能不适合您。

答案3

虽然其他人提到了在达到 80 个字符限制的单词之前换行的工具,但还有另一种工具会尝试在句子结束或开始后不换行,并执行其他操作以提高可读性。 它的用法类似:

echo "…" | fmt -w 80

-w选项指定了文本的最大宽度,但文本将仅使用行的 93%(可以使用 覆盖-g)。

fold文本的格式如下:

Although others mentioned tools that break the lines just before the word that 
hits the 80-character limit, there is also another tool that tries to not break 
the lines just before end of after start of a sentence and does other things 
for better readability. Its usage is similar:

    echo "…" | fmt -w 80

The `-w` option specifies the maximum width of the text, but the text will use 
only 93 percent of the line (this can be overridden by using `-g`).

The long sentence that hits the 80 character column count is this one and here.

这是输出fmt

Although others mentioned tools that break the lines just before the word
that hits the 80-character limit, there is also another tool that tries
to not break the lines just before end of after start of a sentence and
does other things for better readability. Its usage is similar:

    echo "…" | fmt -w 80

The `-w` option specifies the maximum width of the text, but the text will
use only 93 percent of the line (this can be overridden by using `-g`).

The long sentence that hits the 80 character column count is this one
and here.

您会注意到,最后一个(正好是 80 个字符长)被换行了,但不是在第 75 列(80 的 93%),而是在它之前的一个单词,因为我们不希望一行中只有一个单词(在打印的文本等中)。

相关内容