Pet*_*r.O 9 grep colors terminal
为什么 grep 将 ANSI 代码添加\e[K
到其彩色输出中?我看不出它的意义,但显然开发人员可以。它是一个ANSI/VT100 终端代码,用于“清除从当前光标位置到行尾的行”。
在边缘情况下,grep 会导致文本从终端显示中“消失”。例如:
echo -e "ab\rc"
echo -e "ab\rc" |grep --color=always "c"
Run Code Online (Sandbox Code Playgroud)
简单的回显显示:cb
,但彩色显示显示:c
底层编码文本是:echo -e 'ab\r\033[01;31m\033[Kc\033[m\033[K'
但是,没有\e[K
代码, echo -e 'ab\r\033[01;31mc\033[m'
按预期工作!
grep 包含这些\e[K
代码的原因是什么。我正在写一个脚本来允许一个叠加的第二彩色化通,如:c=--color=always; ls $c /bin/gzip | grep $c 'z'
。所以我需要了解为什么 grep 使用\e[K
.
Mic*_*ton 11
您可以通过设置GREP_COLORS
环境变量来更改此行为:
export GREP_COLORS=ne
echo -e "ab\rc" | grep --color=always "c"
Run Code Online (Sandbox Code Playgroud)
从grep
手册页:
ne Boolean value that prevents clearing to the end of line
using Erase in Line (EL) to Right (\33[K) each time a
colorized item ends. This is needed on terminals on
which EL is not supported. It is otherwise useful on
terminals for which the back_color_erase (bce) boolean
terminfo capability does not apply, when the chosen
highlight colors do not affect the background, or when EL
is too slow or causes too much flicker. The default is
false (i.e., the capability is omitted).
Run Code Online (Sandbox Code Playgroud)
它首先将行的其余部分的背景设置为正确的颜色,以防它更早更改(尽管默认情况下不是;有人可能会在他们自己的设置中进行设置)。
您可能还想使用可以设置的其他选项GREP_COLORS
;有关完整详细信息,请参阅手册页。