Coder Perfect

Using linux shell scripting, delete [ and all escape sequences from a file.


We wish to get rid of [ as well as all of the escape sequences.

sed isn’t working, and we’re getting the following error:

$ sed 's/^[//g' oldfile > newfile; mv newfile oldfile;
sed: -e expression #1, char 7: unterminated `s' command

$ sed -i '' -e 's/^[//g' somefile
sed: -e expression #1, char 7: unterminated `s' command

Asked by hasan

Solution #1

Is ansifilter what you’re looking for?

You have two options: (1) enter the physical escape room; (2) enter the figurative escape room (in bash:)

Using keyboard entry:

sed 's/Ctrl-vEsc//g'


sed 's/Ctrl-vCtrl-[//g'

Alternatively, you can utilize the following character escapes:

sed 's/\x1b//g'

Alternatively, for all control characters:

sed 's/[\x01-\x1F\x7F]//g' # NOTE: zaps TAB character too!

Answered by sehe

Solution #2

The correct answer is commandlinefu, which strips ANSI colors as well as movement commands:

Answered by Tom Hale

Solution #3

For my purposes, I was able to get by with the following, but this does not contain all conceivable ANSI escapes:

sed -r s/\x1b\[[0-9;]*m?//g

This disables m instructions, but use: for all escapes (as @lethalman suggested).

sed -r s/\x1b\[[^@-~]*[@-~]//g

Also see “”.

A table of frequent escape sequences is also included.

Answered by Luke H

Solution #4

On Ubuntu, the ansi2txt tool (part of the kbtin package) appears to be working perfectly.

Answered by soorajmr

Solution #5

I don’t have enough reputation to comment on Luke H’s answer, but I wanted to provide the regular expression that I’ve been using to remove all ASCII Escape Sequences.

sed -r 's~\x01?(\x1B\(B)?\x1B\[([0-9;]*)?[JKmsu]\x02?~~g'

Answered by AGipson

Post is based on