How to address ANSI Escape Sequences in sed?

57 views Asked by At

A file with an ASCII-art logo is bloated with 'rgb-black foreground space characters'. Vim shows them as

^[[38;2;0;0;0m ^[[0m

Can I get sed to substitute this with 'regular' space characters, and if so, how?

sed -i 's/\\033\[38;2;0;0;0m \\033\[0m/ /g' $FILE

doesn't do the job on Bash V5.2.15 (up-to-date Debian12 x86_64)

1

There are 1 answers

0
jhnc On
sed -i 's/Ctrl-VEsc\[38;2;0;0;0m Ctrl-VEsc\[0m/ /g' "$FILE"

The escape character is not special to sed, and can be typed directly into a single-quoted string from the bash commandline as shown above. Ctrl-V should be replaced by whatever stty -a shows is assigned as lnext.

To avoid using literal escape characters (which probably won't survive cut&paste, etc), bash's $'' notation could be used with some doubling of backslashes:

sed -i $'s/\033\\[38;2;0;0;0m \033\\[0m/ /g' $FILE

or moving them outside:

sed -i $'s/\033''\[38;2;0;0;0m '$'\033''\[0m/ /g' $FILE

Standard sed does not understand escape (or hex) sequences like \033, although GNU sed does:

sed -i 's/\033\[38;2;0;0;0m \033\[0m/ /g' $FILE