20

I have a bash script that runs and outputs to a text file however the colour codes it uses are also included what i'd like to know is how to remove them from the file, ie

^[[38;1;32mHello^[[39m
^[[38;1;31mUser^[[39m

so I just want to be left with Hello and User

GreyCat
  • 16,251
  • 18
  • 73
  • 108
Lurch
  • 727
  • 2
  • 13
  • 29
  • Related answer using python: http://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python – GreyCat Oct 10 '13 at 17:15
  • 2
    Duplicate: http://unix.stackexchange.com/questions/4527/program-that-passes-stdin-to-stdout-with-color-codes-stripped – GreyCat Oct 10 '13 at 17:16

3 Answers3

14
sed -r "s/\x1B\[(([0-9]{1,2})?(;)?([0-9]{1,2})?)?[m,K,H,f,J]//g" file_name

this command removes the special characters and color codes from the file

these are some of ANSI codes: ESC[#;#H or ESC[#;#f moves cursor to line #, column # ESC[2J clear screen and home cursor ESC[K clear to end of line,

note in case of clear code there is neither number nor semicolon ;

agree with below comment: if the numbers are more than 2 digit kindly use this:

sed -r "s/\x1B\[(([0-9]+)(;[0-9]+)*)?[m,K,H,f,J]//g" filename
Jasen
  • 11,087
  • 2
  • 27
  • 46
sandy_1111
  • 183
  • 2
  • 11
  • there is no guarantee on the number of number parts in the code, those for setting colour can have upto 5 numbers without redundancy. the codes for setting other features (eg linux consile bell frequency) can have more than 2 digits in a row. – Jasen Jul 01 '15 at 05:22
  • agree with you Jasen :-) – sandy_1111 Jul 01 '15 at 11:17
  • 3
    The commas in `[m,K,H,f,J]` are superfluous, right? – Tuetschek May 02 '18 at 13:22
6

My solution:

... | sed $'s/\e\\[[0-9;:]*[a-zA-Z]//g'

The colon is there to support escapes for some old terminal types.

Wiimm
  • 2,430
  • 1
  • 13
  • 22
1

Does this solve the issue?

$ echo "^[[38;1;32mHello^[[39m" | sed -e 's/\^\[\[[0-9;]\{2,\}m//g'
Hello

cheers!!

MacUsers
  • 1,973
  • 3
  • 33
  • 50
  • No, it doesn't, because `^[` represents the ASCII Escape character (Control-[, code 27). – Armali Oct 30 '13 at 09:35
  • @Armali: don't understand your point. According to the OP's requirement, it should work. Can you post an example where it doesn't work? Cheers!! – MacUsers Oct 30 '13 at 15:51
  • Yes... `TERM=xterm tput setf 1|sed -e 's/\^\[\[[0-9;]\{2,\}m//g'|hexdump -C` – Armali Oct 31 '13 at 07:36
  • I don't think that what the OP is after. – MacUsers Oct 31 '13 at 11:29
  • 2
    I think you mean `echo $'\033'"[38;1;32mHello"$'\033'"[39m" | sed -e 's/\^\[\[[0-9;]\{2,\}m//g'` (what you wrote can't be pasted successfully) ,and no it doesn't work. – Jasen Jul 01 '15 at 05:17