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
You could also use the
unbuffer to create a pseudo-tty like this:
echo barney | unbuffer grep barney | sed -n 1,$\ p