I have a file with ANSI colors.
test.txt:
e[0;31mExamplee[0m
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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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
or
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 mplee[0m e[0;31mExample line2e[0m
Method 2
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.
Compare:
echo -e "e[0;31mExamplee[0m foo"
to
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.
Method 3
It should work by default.
E.g. if I do ls --color=always > /tmp/a and than cat /tmp/a, I see the colors. Checking with od confirms that the file uses ANSI colors.
So I think you should check if your terminal supports ANSI colors (and they are enabled).
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0