级联 grep 将颜色代码匹配为模式

Mar*_*ter 5 grep colors

我正在将一个grep命令的输出传输到另一个命令中grep。第一个grep是 using --color=always,因此第一个匹配项是彩色的。实际上,这意味着匹配包含在两个颜色代码之间,即\033[1;31m\033[0m

现在的问题是如果第二个模式是m,那么它匹配上一个匹配的颜色代码:

echo A B C | grep --color=always A | grep m
Run Code Online (Sandbox Code Playgroud)

同样,数字31也会匹配。

有没有办法解决?

更新:

我预计不用说我需要将火柴着色,因此摆脱--color=always对我来说并不是一个令人满意的解决方案。

ter*_*don 6

不要使用grep --color=always,这正是 GNU grep(也许其他人)也有grep --color=autowhich 等效于grep --color单独(来自man grep)的原因:

   --color[=WHEN], --colour[=WHEN]
          Surround  the  matched  (non-empty)  strings,  matching   lines,
          context  lines,  file  names,  line  numbers,  byte offsets, and
          separators (for fields and groups of context lines) with  escape
          sequences  to display them in color on the terminal.  The colors
          are  defined  by  the  environment  variable  GREP_COLORS.   The
          deprecated  environment  variable GREP_COLOR is still supported,
          but its setting does not have priority.  WHEN is never,  always,
          or auto.
Run Code Online (Sandbox Code Playgroud)

我找不到更详细的记录位置,但它基本上检测输出grep是文件还是终端或管道或其他任何内容并相应地采取行动:

$ echo foo | grep --color=always o | grep m
f[01;31mo[m[01;31mo[m
$ echo foo | grep --color=always o >outfile; grep m outfile
f[01;31mo[m[01;31mo[m
Run Code Online (Sandbox Code Playgroud)

比较上面的

$ echo foo | grep --color o >outfile; grep m outfile
$ echo foo | grep --color o | grep m 
$ 
Run Code Online (Sandbox Code Playgroud)

因此,使用该auto选项基本上只会在您可以看到它们时打印颜色。它真的非常聪明,就像一个魅力。这么多,我有:

$ type grep
grep is aliased to `grep --color'
Run Code Online (Sandbox Code Playgroud)


god*_*eek 3

--color就其价值而言,这正是默认为--color=auto和 not的原因--color=always

如果您的目标是“显示包含Am并突出显示匹配Am字符的所有行”,那么最简单的解决方案似乎是在所有匹配之后进行所有突出显示,使用一个egrep 将突出显示重新添加回来。就像是:

{
    echo "A b";
    echo "A m";
    echo "B m";
    echo "Another m";
} | grep 'A' | grep 'm' | egrep --color 'A|m';
Run Code Online (Sandbox Code Playgroud)