To highlight a grep, we use grep --color, however, sometimes either grep does not have highlighting (AIX), or, we want to highlight multiple expressions with different colors.
usage: ls -l | grep -e foo -e bar |./highlight.pl this that foo bar
#!/usr/bin/perl
use Term::ANSIColor;
while(<STDIN>){
for $i (1..15){
next unless(defined($ARGV[$i-1]));
s/($ARGV[$i-1])/&colored($1,"ansi15 on_ansi$i")/gexi;
}
print;
}
Of course, just use an alias or put it in the path and call it just "hl" for sanity. It supports 15 different arguments, but can be extended to the 255 different combinations Linux has.
On some terminals however, you want your own selected colours, in that case, you will need to specify them by hand, for example:
#!/usr/bin/perl
use Term::ANSIColor;
$VERSION = '1.1';
@C = ('black on_yellow','black on_green','black on_cyan','black on_red
+', 'red on_white', 'black on_magenta', 'white on_red', 'white on_blue
+', 'blue on_white', 'yellow on_cyan' );
while(<STDIN>){
for $i (0..$#C){
s/($ARGV[$i])/&colored($1,$C[$i])/gexi if($ARGV[$i]);
}
print;
}
In the latter example, you can specify many more attributes, like bold and underscore, even blink... peruse ANSIColor.pm for examples.
Caveats: Do not grep on digits 0..15 (except as first argument), as the ansi codes also contain numbers...