I use (GNU) fmt
to format longer texts with nice (‘optimal’) line breaks. However, if the text contains any ANSI colour escape sequences (which are never displayed, and only serve to colour the text when displaying it), fmt
considers these as normal characters, and calculates the wrong line lengths.
我使用(GNU)fmt来设置具有良好(“最佳”)换行符的较长文本。但是,如果文本包含任何ANSI颜色转义序列(从不显示,并且仅用于在显示文本时为文本着色),则fmt将这些视为普通字符,并计算错误的行长度。
I’m not sure how good literal escape characters work here, so here’s a simple example using grep
to generate the ANSI sequences. Let’s start with a long string to format.
我不确定文字转义字符在这里有多好用,所以这里有一个使用grep生成ANSI序列的简单示例。让我们从一个长字符串开始格式化。
string="Here’s an example of a rather long \
string with quite a few words in the middle \
that grep chooses to colour red."
If we don’t highlight the grep
matches, everything works fine:
如果我们不突出显示grep匹配,一切正常:
echo $string | grep --color=no i | fmt -w 50
But if we highlight/colour them, fmt
considers the lines containing the letter ‘i’ to be much longer than they really are, and they are shown as rather short lines when displayed in a terminal.
但是如果我们突出显示/着色它们,fmt会认为包含字母“i”的行比实际长得多,并且在终端中显示时它们显示为相当短的行。
echo $string | grep --color=yes i | fmt -w 50
Is there a way to avoid this? For this example I could of course use fmt
before grep
, but when the search string spans several words, this doesn’t work.
有办法避免这种情况吗?对于这个例子,我当然可以在grep之前使用fmt,但是当搜索字符串跨越几个单词时,这不起作用。
3 个解决方案
#1
There doesn't seem to be a good way to resolve that using grep and fmt. I recommend you run fmt first and then use sed instead of grep for searching. For example:
似乎没有一种好方法可以使用grep和fmt来解决这个问题。我建议你先运行fmt,然后使用sed而不是grep进行搜索。例如:
echo The search string will be highlighted red. | fmt -w 50 | sed ":a;$!N;$!ba;s/search[ \n]string/\x1b\[1;31m&\x1b\[0m/g"
#2
Using `grep --colour=auto' instead would solve the problem.
使用`grep --colour = auto'代替可以解决问题。
#3
You can use hmt for this. It was conceived exactly for this scenario.
您可以使用hmt进行此操作。它完全是为这种情况构思的。
Note: I am the author of hmt
.
注意:我是hmt的作者。
#1
There doesn't seem to be a good way to resolve that using grep and fmt. I recommend you run fmt first and then use sed instead of grep for searching. For example:
似乎没有一种好方法可以使用grep和fmt来解决这个问题。我建议你先运行fmt,然后使用sed而不是grep进行搜索。例如:
echo The search string will be highlighted red. | fmt -w 50 | sed ":a;$!N;$!ba;s/search[ \n]string/\x1b\[1;31m&\x1b\[0m/g"
#2
Using `grep --colour=auto' instead would solve the problem.
使用`grep --colour = auto'代替可以解决问题。
#3
You can use hmt for this. It was conceived exactly for this scenario.
您可以使用hmt进行此操作。它完全是为这种情况构思的。
Note: I am the author of hmt
.
注意:我是hmt的作者。