I have a file with ANSI colors.
I would like to display the content of this file in a terminal, like
cat does, but I would like to display the colors as well.
I was looking for a solution to this exact bash question. I nearly missed @Thomas Dickey's comment which provided me with the most elegant solution.
echo -e $(cat test.txt)
Some things which did not work for me are(apparently you cant pipe things to echo)
cat test.txt | echo -e
less -R test.txt
Another issue I had was that echo -e didn't print newlines and contiguous whitespaces within the file nicely. To print those, I used the following.
echo -ne $(cat test.txt | sed 's/$/\\n/' | sed 's/ /\\a /g')
This works for a test.txt file containing
\e[0;31mExa mple\e[0m \e[0;31mExample line2\e[0m
If you're not seeing color from
cat the control characters are probably not intact.
Some tools strip out control characters but leave in the tail end.
echo -e "\e[0;31mExample\e[0m foo"
echo -e "[0;31mExample[0m foo"
You might be able to rebuild the control sequence from what's left, though it's not fool proof as the regex you use might accidentally pull in unintended character sequences, etc. But for example:
echo -e "[0;31mExample[0m foo" | sed "s:\[\([0-9]*[;m]\):^[[\1:g"
would restore the color to the example string.