Ips*_*ich 6 command-line colors text-formatting wrap
这个问题询问关于在某一列换行的问题,人们建议使用fold
orfmt
但据我所知,这些只是计算字符而不允许非打印字符。例如:
fold -w 20 -s <<<`seq 1 25`
Run Code Online (Sandbox Code Playgroud)
正如人们所料,产生:
1 2 3 4 5 6 7 8 9
10 11 12 13 14 15
16 17 18 19 20 21
22 23 24 25
Run Code Online (Sandbox Code Playgroud)
但:
fold -w 20 -s <<<^[[32m`seq 1 25`^[[m
Run Code Online (Sandbox Code Playgroud)
(这里^[
是转义字符)直观应该产生绿色的文字同样的事情,而是产生:
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20
21 22 23 24 25
Run Code Online (Sandbox Code Playgroud)
在绿色文本中。
我看不到任何说明非打印字符的开关,并且标记非打印字符的PS1 方法似乎不适用于fold
或fmt
。
是否有一些东西(最好是标准的东西)可以在考虑不可打印字符的同时包装文本?
编辑:
上面的例子确实是为了简化和演示问题,但我可能过于简化了。为了澄清我的真实示例,我有一些文字是彩色的(使用 ANSI 转义序列),我希望它能够整齐地换行。例如:
Here is some example text that contains ^[[31mred^[[m and ^[[32mgreen^[[m words that I would like to wrap neatly.
Run Code Online (Sandbox Code Playgroud)
^[
转义字符在哪里。
如果我想让它包装到 20 列,我会期望:
Here is some
example text that
contains red and
green words that
I would like to
wrap neatly.
Run Code Online (Sandbox Code Playgroud)
(在“红色”和“绿色”),但由于ANSI转义代码的,因此,它包装:
Here is some
example text
that contains
red and
green words
that I would like
to wrap neatly.
Run Code Online (Sandbox Code Playgroud)
ANSI 转义序列由 shell 解释,而不是由管道解释。因此,您实际上是将文本^[[32m
与序列输出一起插入到折叠命令中。如果你想让整个文本变成绿色,你可以尝试这样的事情:
echo -e "\e[32m"$(seq 1 25 | fold -w 20 -s)"\e[m"
Run Code Online (Sandbox Code Playgroud)
或者
echo -e "\e[32m"; seq -s ' ' 1 25 | fold -w 20 -s; echo -e "\e[m"
Run Code Online (Sandbox Code Playgroud)
请注意,我使用\e
作为转义字符。这可以直接在 bash shell 中进行测试。