0

I have a script that stores text in a file. Some of that text has bash color espcaed characters that I would like to be used when I display the content of that file in a bash shell. How can this be achieved.

Fox example, ScriptOutput.txt contains

Server is \e[92mRUNNING\e[0m

I would normally cat the file and get the content, but cat will not color the "RUNNING" section of that line in the text file. I also tried

echo $(cat ScriptOutput.txt)

but it will print everything in that file in a single line, which is useless for me. Any ideas how to print the content of that file with the colors specified in each line?

Thank you

3
  • 1
    How was the file created? Can you show a hexdump (e.g. xxd) of one coloured line from the file?
    – choroba
    Commented Feb 22, 2016 at 14:35
  • less can interpret ANSI escape codes if called with less -R (can also be set as an environment variable, LESS='-R'). Commented Feb 22, 2016 at 14:42
  • And echo "$(< ScriptOutput.txt)" (same as cat) with quotes would keep the newlines. Commented Feb 22, 2016 at 14:44

3 Answers 3

3

I ended up storing the text using echo and then I cat the file line by line and print it also using echo (echo -e)

Example:

    echo 'Server1 is not \e[92mAVAILABLE\e[0m' >> scriptOutput.txt
    echo 'Server2 is not \e[31mNOT AVAILABLE\e[0m' >> scriptOutput.txt

    cat scriptOutput.txt | while read -r line; do echo -e "$line"; done

I needed to have the script output store in a file but I also needed to print its content in the shell later on with colors. That did the trick Thank you anyway guys

1
  • why you don't use the sed pipe?
    – OkieOth
    Commented Feb 23, 2016 at 15:01
1

Instead of the string \e, you want to have a literal escape character in your script. How you can enter this depends on your terminal and text editor.

For me (using nano from the OS X terminal, please withhold your disdain!) I press Esc followed by Shift-V. nano tells me it's in "Verbatim Input" mode. Then I can hit the escape key and get a literal escape character (represented on screen by ^[).

This will demonstrate a universal method to insert the escape character using printf:

printf '\033[44mfoo\033[0m\nbar\n\033[92mbaz\033[0m\n' > foo.txt
cat foo.txt
0

You can pipe your script output through sed and replace there the '\e' character with the hex value of ESC. The result should be colored.

cat ScriptOutput.txt | sed -e 's-\\e-\x1b-g'

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