The characters ^[[37m and ^[[0m are part of the ANSI escape sequences (CSI codes).
See also these specifications.
Using GNU sed
sed -e 's/\x1b\[[0-9;]*m//g'
\x1b (or \x1B) is the escape special character
(GNU sed does not support alternatives \e and \033)
\[ is the second character of the escape sequence
[0-9;]* is the color value(s) regex
m is the last character of the escape sequence
Using the macOS default sed
Mike suggests:
sed -e $'s/\x1b\[[0-9;]*m//g'
The macOS default sed does not support special characters like \e as pointed out by slm and steamer25 in the comments.
To install gsed.
brew install gnu-sed
Example with OP's command line
(OP means Original Poster)
perl -e 'use Term::ANSIColor; print color "white"; print "ABC\n"; print color "reset";' |
sed 's/\x1b\[[0-9;]*m//g'
Improvements
Flag -e is optional for GNU sed but required for the macOS default sed:
sed 's/\x1b\[[0-9;]*m//g' # Remove color sequences only
Tom Hale suggests to also remove all other escape sequences using [a-zA-Z] instead of just the letter m specific to the graphics mode escape sequence (color):
sed 's/\x1b\[[0-9;]*[a-zA-Z]//g' # Remove all escape sequences
But [a-zA-Z] may be too wide and could remove too much. Michał Faleński and Miguel Mota propose to remove only some escape sequences using [mGKH] and [mGKF] respectively.
sed 's/\x1b\[[0-9;]*[mGKH]//g' # Remove color and move sequences
sed 's/\x1b\[[0-9;]*[mGKF]//g' # Remove color and move sequences
sed 's/\x1b\[[0-9;]*[mGKHF]//g' # Remove all
Last escape
sequence
character Purpose
--------- -------------------------------
m Graphics Rendition Mode (including color)
G Horizontal cursor move
K Horizontal deletion
H New cursor position
F Move cursor to previous n lines
Britton Kerin indicates K (in addition to m) removes the colors from gcc error/warning. Do not forget to redirect gcc 2>&1 | sed....
Using perl
The version of sed installed on some operating systems may be limited (e.g. macOS). The command perl has the advantage of being generally easier to install/update on more operating systems. Adam Katz suggests to use \e (same as \x1b) in PCRE.
Choose your regex depending on how much commands you want to filter:
perl -pe 's/\e\[[0-9;]*m//g' # Remove colors only
perl -pe 's/\e\[[0-9;]*[mG]//g'
perl -pe 's/\e\[[0-9;]*[mGKH]//g'
perl -pe 's/\e\[[0-9;]*[a-zA-Z]//g'
perl -pe 's/\e\[[0-9;]*m(?:\e\[K)?//g' # Adam Katz's trick
Example with OP's command line:
perl -e 'use Term::ANSIColor; print color "white"; print "ABC\n"; print color "reset";' \
| perl -pe 's/\e\[[0-9;]*m//g'
Usage
As pointed out by Stuart Cardall's comment, this sed command line is used by the project Ultimate Nginx Bad Bot (1000 stars) to clean up the email report ;-)