Examining the output from

perl -e 'use Term::ANSIColor; print color "white"; print "ABC\n"; print color "reset";'

in a text editor (e.g., vi) shows the following:

^[[37mABC
^[[0m

How would one remove the ANSI color codes from the output file? I suppose the best way would be to pipe the output through a stream editor of sorts.

The following does not work

perl -e 'use Term::ANSIColor; print color "white"; print "ABC\n"; print color "reset";' | perl -pe 's/\^\[\[37m//g' | perl -pe 's/\^\[\[0m//g'
link|improve this question

64% accept rate
feedback

2 Answers

up vote 3 down vote accepted

Using sed:

perl -e 'use Term::ANSIColor; print color "white"; print "ABC\n"; print color "reset";' | 
sed 's/\x1b\[[0-9]*m//g'
  • \x1b is the escape special character
  • \[ is the second character of color statement
  • [0-9]* is the color value
  • m is the last character of color statement

sed is enough, but you can still use perl instead of sed:

perl -e 'use Term::ANSIColor; print color "white"; print "ABC\n"; print color "reset";' | 
perl -pe 's/\x1b\[[0-9]*m//g'
link|improve this answer
Wonderful, thank you so much. – user001 Jan 21 at 1:56
feedback

What is displayed as ^[ is not ^ and [; it is the ASCII ESC character, produced by Esc or Ctrl[ (the ^ notation means the Ctrl key).

ESC is 0x1B hexadecimal or 033 octal, so you have to use \x1B or \033 in your regexes:

perl -pe 's/\033\[37m//g; s/\033[0m//g'

perl -pe 's/\033\[\d*(;\d*)*m//g'
link|improve this answer
Wonderful, thank you so much. – user001 Jan 21 at 1:56
feedback

Your Answer

 
or
required, but never shown

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