#!/usr/bin/perl use strict; use warnings; use Term::ANSIColor; use List::Util qw( min ); use Getopt::Std; getopts( 'c:x' ); my @color = split /,/, our $opt_c || 'bold red'; @ARGV or die <<"END_USAGE"; usage: @{[ colored( 'hl [ -c colour ] [ -x ] pattern [ file... ] [ < i +nput ]', 'bold' ) ]} You can use capturing parens in your pattern. In that case, you can supply multiple attributes separated by commas, which will be used to individually colour the submatches. @{[ colored( '-x', 'bold' ) ]} will supress lines without match +es. END_USAGE my $rx = shift; $rx = qr/$rx/; while ( <> ) { s{ $rx }{ colored_match() }gex or not( our $opt_x ) or next; print; } sub colored_match { my @START = @-; my @END = @+; my $last = min( $#color, $#START ); if ( $last ) { push @START, $END[ 0 ]; push @END, $END[ 0 ]; $END[ 0 ] = $START[ 0 ]; my $str; for my $i ( 0 .. $last ) { $str .= colored( substr( $_, $START[ $i ], $END[ $i ] - $START[ $i ] ), $color[ $i ], ) unless $i == 0; $str .= colored( substr( $_, $END[ $i ], $START[ $i + 1 ] - $END[ $i ] +), $color[ 0 ], ); } return $str; } else { return colored( substr( $_, $START[ 0 ], $END[ 0 ] - $START[ 0 ] ), $color[ 0 ], ); } }

In reply to Input highlighter / visual grep by Aristotle

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.