Using sed to color the output from a command on solaris

\xNN is an escape sequence in GNU sed, but it is not standard, and in particular it is not available on Solaris.

You can include a literal escape character in your script, but that would make it hard to read and edit.

You can use printf to generate an escape character. It understands octal escapes, not hexadecimal.

esc=$(printf '\033')
echo "test" | sed "s,.*,${esc}[31m&${esc}[0m,"

You can call tput to generate the replacement text in the call to sed. This command looks up escape sequences in the terminfo database. In theory, using tput makes your script more portable, but in practice you're unlikely to encounter a terminal that doesn't use ANSI escape codes.

echo "test" | sed "s,.*,$(tput setaf 1)&$(tput sgr0),"

It would be easier to use tput

tput setaf 1; somecommand; tput sgr0


tput setaf 1
tput sgr0

This sets the foreground to red, runs somecommand which will then display the output in red then clears the color sequence. This works at least with bash, zsh and ksh.

See tmux(1) and terminfo(5) for more information about what you can do with tput.