Best way to remove ANSI color escapes in Unix
I have a perl progaram its prints output with color. if I rediect the output in the file and open it in vi I see color special character. something like this.
^[[31;43mAnd this is red on_yellow too^[[0m
What is the best way to remove this color character from the output file?
Thanks
Update:
I tried thid regex. it works for me:
cat -v a|head
^[[30;41mThis is black on_red^[[0m
^[[30;41mAnd this is black on_red too^[[0m
^[[30;42mThis is black on_green^[[0m
^[[30;42mAnd this is black on_green too^[[0m
^[[30;43mThis is black on_yellow^[[0m
^[[30;43mAnd this is black on_yellow too^[[0m
^[[30;44mThis is black on_blue^[[0m
^[[30;44mAnd this is black on_blue too^[[0m
^[[30;45mThis is black on_magenta^[[0m
^[[30;45mAnd this is black on_magenta too^[[0m
$ cat -v a|head|perl -lane 's/\^\[\[\d+(;\d+)*开发者_开发问答m//g; print'
This is black on_red
And this is black on_red too
This is black on_green
And this is black on_green too
This is black on_yellow
And this is black on_yellow too
This is black on_blue
And this is black on_blue too
This is black on_magenta
And this is black on_magenta too
The Perl module Term::ANSIColor
provides a function, colorstrip()
, to do just this. For example,
ls --color | perl -MTerm::ANSIColor=colorstrip -ne 'print colorstrip($_)'
Module Term::ANSIColor
is part of the Perl core.
Coincidentally I just had to solve this problem, and this is the regexp I came up with:
while (<>) {
s/\e\[[\d;]*[a-zA-Z]//g;
print;
}
I just derived this by examining some example output (in particular, the output of grep --color=always ...
), so it may not cover all the escapes you expect.
According to the information on this site, the last character class could probably be shorten from [a-zA-Z]
to just [mK]
.
精彩评论