Lately there has been a tendency by command line tools to use fancy ANSI colors in their log output (for example, NPM and a host of nodejs based tools, rvm, docker, and a few other "modern" tools).

This makes it nice to read on the screen(*), but not so nice when you want to pipe the output to a log file or through a transport that does not handle ANSI well, like various remote execution tools and web based monitoring solutions. A lot of more mature tools at least had the decency to detect when the output is not a TTY and disable color, but not with those new fangled "user friendly" CLIs - which leaves me the try to get rid of the ANSI colors by piping the output through yet another process.

Sed-ing the output through s/\x1B\[[0-9]*\w//g seems to get the job done, but is there a cleaner approach then just copy pasting regular expressions into all of my scripts?

(*) at least until the the tool tries to display errors in dark red on your dark background terminal.

  • 2
    See: unix.stackexchange.com/questions/14684/… - unix.stackexchange.com/questions/111899/… stackoverflow.com/questions/17998978/… superuser.com/questions/380772/… -- Between 4+ questions over a span of 3 years across 3 sites we have only gotten answers to use a tool that does regex replacement/removal. I would guess there isn't anything better. – Zoredache Jan 14 '15 at 18:44
  • About the only thing that seems up for debate is which regex is the best for which situation. – Zoredache Jan 14 '15 at 18:45
  • 1
    is there a cleaner approach then just copy pasting regular expressions into all of my scripts? - Save your cleanup filter into a file called '/usr/local/bin/stripttycolor.sh` or something? That way you have the regex confined to a single location? – Zoredache Jan 14 '15 at 18:47
  • 3
    If you know that you will be writing the output to a file, the easiest thing to do (at least for NPM) is to run with the --no-color flag. Many other commands also have similar flags. – Moshe Katz Jan 15 '15 at 23:44
  • @MosheKatz: unfortunately not all commands do, for example bower. – Guss Jan 18 '15 at 13:34

"ansifilter -p" might be useful to you...

It's in the Fedora repos; -p specifies plain output:

Name        : ansifilter
From repo   : updates
Summary     : ANSI terminal escape code converter
URL         : http://www.andre-simon.de/doku/ansifilter/ansifilter.php
License     : GPLv3+
Description : Ansifilter handles text files containing ANSI terminal escape codes.
            : The command sequences may be stripped or be interpreted to generate formatted
            : output (HTML, RTF, TeX, LaTeX, BBCode).
  • Works nicely, now I just need to get it packaged for Ubuntu :-) – Guss Jan 29 '15 at 13:58

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.