Boston Linux & Unix (BLU) Home | Calendar | Mail Lists | List Archives | Desktop SIG | Hardware Hacking SIG
Wiki | Flickr | PicasaWeb | Video | Maps & Directions | Installfests | Keysignings
Linux Cafe | Meeting Notes | Blog | Linux Links | Bling | About BLU

BLU Discuss list archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Discuss] sed and ANSI sequences



I have a script at work that colorizes command outputs.  I've mentioned it here before.  I have
the colors defined in environment variables:
COLOR_ERROR='\e[37;41m'
COLOR_GOOD='\e[32;40m'
COLOR_RESET='\e[0m'
COLOR_WARN='\e[33;40m'

I want to move from using Perl for this to sed.  When I try, the ANSI sequences aren't being
executed so I see them instead of the text colorized.  Here's a small example:

> echo "This is a [WARNING] message " | perl -pe
's/(.*\[WARNING\].*)/'${COLOR_WARN}'$1'${COLOR_RESET}'/g;'

This is a [WARNING] message
(appears in yellow on black as intended)

> echo "This is a [WARNING] message " | sed -e 's/.*[WARNING].*/'${COLOR_WARN}'&'${COLOR_RESET}'/g;'

e[33;40mThis is a [WARNING] message e[0m
(escape codes appear around black on white text)

I even tried adding an extra escape backslash
> echo "This is a [WARNING] message " | sed -e
's/.*[WARNING].*/\'${COLOR_WARN}'&\'${COLOR_RESET}'/g;'

\e[33;40mThis is a [WARNING] message \e[0m
(escape codes appear prefixed with \ around black on white text)

Since sed should not be interpreting the escape sequences, how should it be working any differently?

PS: I did see one working example at
http://travelingfrontiers.wordpress.com/2010/08/22/how-to-add-colors-to-linux-command-line-output/
sed ''/crit/s//$(printf "\033[31mCRITICAL\033[0m")/g''

However, it relies on the printf command, which means (1)launching another process and 2) not
using sed's buffers, so I can't have a series of sed operations in one command.

Also, I don't understand the doubled single quotes.  That should be the equivalent of no quotes at
all.







BLU is a member of BostonUserGroups
BLU is a member of BostonUserGroups
We also thank MIT for the use of their facilities.

Valid HTML 4.01! Valid CSS!



Boston Linux & Unix / webmaster@blu.org