Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to remove ANSI color escapes in Unix

Tags:

unix

perl

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
like image 462
sfgroups Avatar asked Sep 12 '11 22:09

sfgroups


People also ask

How do I delete ANSI escape sequences?

You can use regexes to remove the ANSI escape sequences from a string in Python. Simply substitute the escape sequences with an empty string using re. sub(). The regex you can use for removing ANSI escape sequences is: '(\x9B|\x1B\[)[0-?]

What is <UNK>x1B?

The code containing only 0 (being \x1B[0m ) will reset any style property of the font. Most of the time, you will print a code changing the style of your terminal, then print a certain string, and then, the reset code.

What is ANSI escape sequences Python?

ANSI escape sequences are a standard for in-band signaling to control cursor location, color, font styling, and other options on video text terminals and terminal emulators. Certain sequences of bytes, most starting with an ASCII escape character and a bracket character, are embedded into text.


1 Answers

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.

like image 87
mavit Avatar answered Oct 11 '22 11:10

mavit