Question: I have some script that produces output with colors and I need to remove the ANSI codes.

```
#!/bin/bash

exec > >(tee log)   # redirect the output to a file but keep it on stdout
exec 2>&1

./somescript

```

The output is (in log file):

```
java (pid  12321) is running...@[60G[@[0;32m  OK  @[0;39m]

```

I didn't know how to put the ESC character here, so I put `@` in its place.

I changed the script into:

```
#!/bin/bash

exec > >(tee log)   # redirect the output to a file but keep it on stdout
exec 2>&1

./somescript | sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"

```

But now it gives me (in log file):

```
java (pid  12321) is running...@[60G[  OK  ]

```

How can I also remove this '`@[60G`?

Maybe there is a way to completely disable coloring for the entire script?

Answer: 
For Mac OSX or BSD use

```
./somescript | sed $'s,\x1b\\[[0-9;]*[a-zA-Z],,g'

```
I had a similar problem. All solutions I found did work well for the color codes but did not remove the characters added by `"$(tput sgr0)"` (resetting attributes).

Taking, for example, the solution in the [comment by davemyron](https://stackoverflow.com/questions/17998978/removing-colors-from-output#comment76844503_18000433) the length of the resulting string in the example below is 9, not 6:

```
#!/usr/bin/env bash

string="$(tput setaf 9)foobar$(tput sgr0)"
string_sed="$( sed -r "s/\x1B\[[0-9;]*[JKmsu]//g" <<< "${string}" )"
echo ${#string_sed}

```

In order to work properly, the regex had to be extend to also match the sequence added by `sgr0` ("`\E(B`"):

```
string_sed="$( sed -r "s/\x1B(\[[0-9;]*[JKmsu]|\(B)//g" <<< "${string}" )"

```