How to keep colored output using sed

colorslsosxpipesed

I'm using the sed command and I want to keep colored output from the previous command. The output of ls is colored, but the output of sed is not. I'm using OSX.

ls -la | sed -En  '/Desktop/q;p'

Best Answer

On macOS, the ls is not GNU ls and does not accept the --color=always option that Linux users might expect for this functionality.

In the macOS version of ls, the colors are controlled by two variables: $CLICOLOR and $CLICOLOR_FORCE. If the former is defined, the terminal specified by $TERM supports color, and the output is to a terminal, then this output will be colored, much like GNU's --color=auto option. If the latter variable is defined as well, the final condition is dropped, behaving like GNU's --color=always.

So to have color passed through to sed, you would need something like the following:

CLICOLOR_FORCE=1 ls -la | sed -En '/Desktop/q;p'