10

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'
13

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'
|improve this answer|||||
  • macOS's ls does have the -G option to enable color as well, but I'm not sure how it behaves in a pipeline. – 8bittree Jan 29 '19 at 19:01
  • 2
    @8bittree Passing -G is equivalent to defining $CLICOLOR (and therefore not sufficient) – Fox Jan 29 '19 at 19:27
6

I'll blindly guess that your distribution, like many, has an alias that maps ls to ls --color=auto. ls -la --color=always | sed … should work.

(The auto setting makes, broadly speaking, ls check if its output goes to the display or not, and only color for the display. The reason for this is that color is realized by escape sequences, i.e. invisible command characters, so a program might confuse them for part of the filename, things like that.)

|improve this answer|||||
  • 3
    The blind guess is wrong. OSX is not a Linux distribution and does not use a GNU userland – Fox Jan 29 '19 at 12:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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