更新:

更新:

我正在將一個命令的輸出傳輸grep到另一個命令grep。第一個grep是使用--color=always,以便第一個匹配項是彩色的。實際上,這意味著匹配包含在兩個顏色代碼之間,即\033[1;31m\033[0m

現在的問題是,如果第二個模式是m,那麼它與前一個匹配的顏色代碼匹配:

echo A B C | grep --color=always A | grep m

同樣,數字31也會匹配。

有沒有辦法解決?

更新:

我預計不言而喻,我需要為火柴上色,所以擺脫--color=always對我來說並不是一個令人滿意的解決方案。

答案1

不要使用grep --color=always,這正是為什麼 GNU grep(也許其他人)也有grep --color=auto相當於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.

我找不到更詳細的記錄,但它基本上檢測輸出是否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

比較以上

$ echo foo | grep --color o >outfile; grep m outfile
$ echo foo | grep --color o | grep m 
$ 

因此,使用該auto選項基本上只會在您可以看到顏色時列印顏色。它真的非常聰明,而且就像一個魅力。如此之多,我有:

$ type grep
grep is aliased to `grep --color'

答案2

--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';

答案3

實際用例是什麼?如果你想A在所有包含的行中使用顏色代碼m,你可以簡單地反轉greps:

echo A B C | grep m | grep --color=always A

或者,如果您要在原始輸出中尋找文字,m則需要排除先前的所有顏色代碼grep m,但列印結果顏色代碼。執行此操作的一種方法是使用nl對輸出的行進行編號,grep對於後跟 的行號m,僅保存該輸出中的行號,然後使用sed -n僅列印顏色編碼輸出中的行。

相關內容