Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Why does grep add ANSI code \e[K to its colored output? I can't see the point of it, but obviously the developers can. It is an ANSI/VT100 Terminal code which is used to "Clear line from current cursor position to end of line".

In a fringe case, grep can cause text to "vanish" from the terminal display. For example:

echo -e "ab\rc"
echo -e "ab\rc" |grep --color=always "c"

The simple echo displays: cb, but the colorized display shows: c

The underlying encoded text is: echo -e 'ab\r\033[01;31m\033[Kc\033[m\033[K' However, without the \e[K codes, echo -e 'ab\r\033[01;31mc\033[m' works as expected!

What is the reason for grep's inclusion of these \e[K codes. I'm writing a script to allow for overlaying of a second colorizing pass, as in: c=--color=always; ls $c /bin/gzip | grep $c 'z'. so I need to understand why grep uses \e[K.

share|improve this question

1 Answer 1

up vote 6 down vote accepted

You can change this behavior by setting the GREP_COLORS environment variable:

export GREP_COLORS=ne
echo -e "ab\rc" | grep --color=always "c"

From the grep man page:

          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).

It's done in the first place to set the background of the rest of the line to the correct color, in case it was changed earlier (though by default it isn't; somebody might set it up to do so in their own settings).

You may also want to play with the other options that can be set in GREP_COLORS; see the man page for full details.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.