3

I want to see color output when in stdout to the console, but I want to remove it in a captured copy of the output from the tee command.  In my case,

command_that_writes_color_to_stdout | tee file

I'd like the file to be clean of ANSI color sequences, etc., as it makes greping the log file fun later:

echo -e "color \033[1;31mRED\033[0m output" | tee test.log

In this case, color is written to the console and also into the file "test.log".

color ^[[1;31mRED^[[0m output

Is there a way to strip ANSI sequences only for the tee's output to file?

Tried to make tee see my terminal is unaware of colors (env vars, sub-shells) but tee happily just writes what it is given.  I want the color for the console output (for human consumption, it's great) but do not want color in the log file copy of the output.

echo -e "color \033[1;31mRED\033[0m output" | TERM=dumb tee test.log ; od -c test.log

I found many who want color codes in their "piped to tee" output (usually when the first program is aware of something being able to display color), but I'm not finding an question/answer to do the reverse.

1

2 Answers 2

2

If you’re using bash, you can remove all colors (graphic renditions) with

echo -e "color \033[1;31mRED\033[0m output" | tee >(sed $'s/\033[[][^A-Za-z]*m//g' > test.log)

or all ANSI escape sequences with

echo -e "color \033[1;31mRED\033[0m output" | tee >(sed $'s/\033[[][^A-Za-z]*[A-Za-z]//g' > test.log)

(I have tested this, but not exhaustively.)

P.S. If you want to append to the log file, use >> test.log inside the parentheses; tee -a won’t do it.

2

With zsh, and ansi2txt from colorized-logs¹:

command_that_writes_color_to_stdout >&1 > >(ansi2txt > file)

zsh does implement a tee-like behaviour when a fd is redirected more than once for writing.


¹ It's available in the eponymous package on Debian/Ubuntu however note that the algorithm is rather crude, see Removing control chars (including console codes / colours) from script output for potentially finer / tighter colouring filters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.