Using empty line as context “group-separator” for grep

colorsgrepperl

I need grep output with context, in color, and blank lines as group separator. In this question, I learned how to define custom group-separator, and I have constructed my grep command like this:

grep --group-separator="" --color=always -A5

but the group separator is actually not empty, instead it still contains the color code (i.e. [[36m[[K[[m[[K). This is because I am using --color=always. But I need color in my grep command, and I need separator to be blank line (for further processing)

How can I combine these two conditions?

Best Answer

If you use the GREP_COLORS environment variable you can control specific colors for each type of match. man grep explains the use of the variable.

The following command will print a colored match, but nothing on the line that separates the group, just a blank line. Piped through od you'll see the color escape before and after the match, but only \n\n at the group separation.

GREP_COLORS='ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=' grep --group-separator="" --color=always -A5

Unsetting the se component will suppress the printing of color in the group separator.

Since my example above used all of the default values for GREP_COLORS the following will work as well.

GREP_COLORS='se=' grep --group-separator="" --color=always -A5

If you're not using a bashlike shell, you might need to export GREP_COLORS first.