Command-Line Colors – How to Preserve ANSI Escape Codes When Piping

colorscommand lineescape-characterspipe

I sometime want to pipe the color-coded output fror a process, eg. grep… but when I pipe it to another process, eg. sed, the color codes are lost…

Is the some way to keep thes codes intact ?

Here is an example which loses the colored output:

echo barney | grep barney | sed -n 1,$\ p   

Best Answer

Many programs that generate colored output detect if they're writing to a TTY, and switch off colors if they aren't. This is because color codes are annoying when you only want to capture the text, so they try to "do the right thing" automatically.

The simplest way to capture color output from a program like that is to tell it to write color even though it's not connected to a TTY. You'll have to read the program's documentation to find out if it has that option. (e.g., grep has the --color=always option.)

You could also use the expect script unbuffer to create a pseudo-tty like this:

echo barney | unbuffer grep barney | sed -n 1,$\ p
Related Question