Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Color highlighted perl grep

by FreeBeerReekingMonk (Deacon)
on Feb 23, 2015 at 17:49 UTC ( [id://1117566]=CUFP: print w/replies, xml ) Need Help??

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...

Replies are listed 'Best First'.
Re: Color highlighted perl grep
by Your Mother (Archbishop) on Feb 23, 2015 at 18:13 UTC

    This looks fun, though didn’t try it. I use App::Ack. It colors output. Not sure how/if it could fit into your applet. (Note you have a bad shebang on your second code block.)

      thanks Your Mother for the ack suggestion: it seems a sweety.
      FreeBeerReekingMonk++ for esording with a cool use for Perl; you'll be sure delighted by the amount of cool things Perl can do.

      Consider a view of "em" - Emphasize text using regular expressions as instructive tour of a different approach to the matter.
      L*
      There are no rules, there are no thumbs..
      Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
        Thank you very much for the em suggestion. using that now for structuring colored output. :)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://1117566]
Approved by Old_Gray_Bear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2024-04-26 00:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found