Highlight command's output with colors using sed
Submitted by Bram Schoenmakers on 2 October, 2008 - 12:09.
For some reason I wanted to highlight some lines during a rsync(1) session, those lines indicating that a file is going to be deleted. Doing the following command right on the command line didn't work:
rsync -nvz bram@musicbox:/home/bram/ /home/bram/ | sed -e 's/^deleting.*$/\\033[41m\\033[37m&\033[0m/'
Because you'll see this garbage instead:
...
Music/Favorites/Right Said Fred - I'm Too Sexy.wma
\033[41m\033[37deleting Music/Favorites/Paris Hilton - Stars Are Blind.wma\033[37m
Music/Favorites/Vengaboys - Sha La La La La.wma
...
Music/Favorites/Right Said Fred - I'm Too Sexy.wma
\033[41m\033[37deleting Music/Favorites/Paris Hilton - Stars Are Blind.wma\033[37m
Music/Favorites/Vengaboys - Sha La La La La.wma
...
No matter how you escape this, it won't work. These color codes should be echoed with echo -e, but that makes the sed expression even more unreadable than it already is. So it's better to do this from a script and define some variables with the color codes first:
#!/bin/sh
RED=`echo -e '\033[41m\033[37m'`
NORMAL=`echo -e '\033[0m'`
rsync -nvz bram@musicbox:/home/bram/ /home/bram/ | sed -e 's/^deleting.*$/$RED&$NORMAL/'
And now we'll get the output we desire:
...
Music/Favorites/Right Said Fred - I'm Too Sexy.wma
deleting Music/Favorites/Paris Hilton - Stars Are Blind.wma
Music/Favorites/Vengaboys - Sha La La La La.wma
...
Music/Favorites/Right Said Fred - I'm Too Sexy.wma
deleting Music/Favorites/Paris Hilton - Stars Are Blind.wma
Music/Favorites/Vengaboys - Sha La La La La.wma
...
You can find all possible color codes on this page.