You'd think there'd be a utility for that, but I couldn't find it. However, this Perl one-liner should do the trick:
perl -pe 's/\e\[?.*?[\@-~]//g'
Example:
$ command-that-produces-colored-output | perl -pe 's/\e\[?.*?[\@-~]//g' > outfile
Or, if you want a script you can save as stripcolorcodes
:
#! /usr/bin/perl
use strict;
use warnings;
while (<>) {
s/\e\[?.*?[\@-~]//g; # Strip ANSI escape codes
print;
}
If you want to strip only color codes, and leave any other ANSI codes (like cursor movement) alone, use
s/\e\[[\d;]*m//g;
instead of the substitution I used above (which removes all ANSI escape codes).
isatty(stdin)
before doing so. Mind to share what is that program?cat
- quick test I rangrep --color=auto myusername /etc/passwd
gives me my username in red with white text elsewhree.grep --color=auto myusername /etc/passwd | cat
gives me plain white textgrep --color=auto
avoids producing colored output when standard output is not a terminal. I'm talking about a command that unconditionally outputs color codes. (As alex points out above, such behavior is arguably a bug, but sometimes we need to work with imperfect software that we can't easily fix ourselves, and that's what this question is about.)grep --colour=always myusername /etc/passwd | cat
keeps the username in red.