Cascaded grep matches color code as pattern

colorsgrep

I am piping output of one grep command into another grep. The first grep is using --color=always, so that the first match is colored. In practice, that means that the match is enclosed between two color codes, i.e. \033[1;31m and \033[0m.

Now the problem is if the second pattern is m, then it matches the color code of the previous match:

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

Similarly, the number 31 would also match.

Is there any way around this?

UPDATE:

I expected it will go without saying that I need the match to be colored, so getting rid of --color=always is not a satisfactory solution for me.

Best Answer

For what it's worth, this is exactly the reason why --color defaults to --color=auto and not --color=always.

If your goal is "Show me all lines that contain both A and m and highlight the matching A and m characters", it seems like the simplest solution would be to do all the highlighting after all of the matching, using one egrep to add the highlighting back in. Something like:

{
    echo "A b";
    echo "A m";
    echo "B m";
    echo "Another m";
} | grep 'A' | grep 'm' | egrep --color 'A|m';
Related Question