Display file with ANSI colors

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         mple\e[0m
\e[0;31mExample line2\e[0m

Tags:

Terminal

Bash