I'm a bit lost on why I need all those backslashes for this to print "Hello World" with the correct colors.

xxx@yyy:/tmp$ echo $Red
xxx@yyy:/tmp$ echo $Red
\033[0;31m    xxx@yyy:/tmp$ echo -e "Hello ${Red} World" | sed "s/^/\\\\\\${Blue}/g" | xargs echo -e
Hello  World

What's the reason for that? Is there any other easier way to sed the colors into the original echo? I'll be needing to do something similar, where I take some text files and I'll try to punch in colors before viewing it in the console.


  • Backslashes are both string escapes and regexp escapes. So you need to multiply them so that sed will output them literally.
    – Barmar
    Commented Jan 24, 2017 at 21:02

1 Answer 1


You don't need to combine the color codes and the text to be output into the same echo command if all you are doing is coloring the entirety of the text at once:

red="$(echo -e "\033[0;31m")"
reset="$(echo -e "\033[0m")"
echo "$red"
echo "This text is red."
echo "$reset"

If you're trying to change embedded color codes; you similarly don't need to rip out the entire escape sequence. To change red text to yellow, you can:

echo "$color_festooned_text" | sed 's/;31/;33/g'
  • I need to color arbitrary pieces of text (for instance, any IP in a log file). Would this serve that purpose? Commented Jan 24, 2017 at 21:14
  • 1
    You can use sed once you have your coloring definitions done with things like sed "s/some_expression/$red&$reset/". For example, this will turn all vowels red: sed "s/[aeiou]/$red&$reset/g".
    – DopeGhoti
    Commented Jan 24, 2017 at 21:38
  • One last question. As this will be used to pipe through large amounts of text, some of it shown in real-time, wouldn't this method have a serious impact on performance? We're pretty much several times per line spawning a new shell. Commented Jan 24, 2017 at 22:23
  • If you build one large sed script to perform all of your substitutions and insertions, you will only be spawning one process per line.
    – DopeGhoti
    Commented Jan 24, 2017 at 23:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .