9

I have a file with ANSI colors.

test.txt:
\e[0;31mExample\e[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.

  • 3
    Using less -R, for instance. – Thomas Dickey Feb 14 '16 at 11:43
  • What does your cat print? – techraf Feb 14 '16 at 11:57
  • 1
    OP's question had too many possible answers to be interesting. Start with echo -e $(cat test.txt). – Thomas Dickey Feb 14 '16 at 16:31
6

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
  • Good answer, but \a rings the bell for me. I changed your second sed command to sed 's/ /\\033\\a /g' which doesn't ring the bell. – hawk Nov 14 '18 at 3:04
  • 1
    After further testing and finding more inconsistencies in different terminal programs (iTerm, Atom/nuclide), I've found it best to just wrap $(cat file.txt) in double quotes and add a newline at the end – no need for sed – so: echo -ne "$(<file.txt)" \\n or echo -ne "$(cat <<"EOF" . . . EOF)" \\n. That also prevents bash from performing glob expansion in the text. – hawk Nov 14 '18 at 21:40
1

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;31mExample\e[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.

-1

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).

  • 1
    This did not answer the question. – Thomas Dickey Feb 14 '16 at 16:23
  • 1
    No. less -R actually resolved the issue for me. – Ken Ingram Jan 1 at 2:25

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.