Filtering output on linux with color

Posted by the ManGeek

Friday, June 3rd 2011 6:52 pm CDT

Last night I found myself desperate to read the output of tail but looking for specific content. (Basically tailing a log file and needing to have the fields pop out at me.) There's no easy colorize command in linux so I did some digging, found something similar and modified it. (This is based on Kenny Moen's blog entry [www.functor.be] about baretail on unix.) Anyway, the following perl script will allow any content to be highlighted using a simple regex and a pipe.

For example, to highlight an entire line wherever named is listed:
tail -f /var/log/messages | colorize --highlight "blue:.*named.*"

Or to highlight the incoming interface and outgoing interface on a firewall log with red for the inside and green for the outside:
tail -f /var/log/messages | colorize --highlight "red:w+=eth0" --highlight "green:w+=eth1"

Enjoy!

#!/usr/bin/perl
use Getopt::Long qw(:config pass_through);

my %colors =
(
   'red'     => '41;37;1m',
   'green'   => '42;37;1m',
   'yellow'  => '43;30;1m',
   'blue'    => '44;37;1m',
   'magenta' => '45;37;1m',
   'cyan'    => '46;30;1m',
   'white'   => '47;30;1m'
);

my @highlights;
GetOptions ("highlight=s" => \@highlights);

my $tailargs;
for(my $c = 0; $c < scalar(@ARGV); $c++)
{
   $tailargs .= ' ' . $ARGV[$c];
}

my $highlightargs;
for(my $c = 0; $c < scalar(@highlights); $c++)
{
   my @data   = split(/:/, $highlights[$c], 2);
   my $color  = $colors{$data[0]};
   my $search = $data[1];

   $highlightargs .= "s/($search)/\033\[$color\$1\033\[0m/gi; ";

}

while (<>)
{
        eval $highlightargs;
        print $_;
}

Trackback URL: http://www.mangeek.com/blogc/59track.html

Comments (0)

Add Comment

Name:
Subject:
Comment:

Note: HTML is allowed but limited to the following: <a>, <p>, <br>, <em>, <strong>, <b>, <i>, <blockquote>, <ol>, <ul>, and <li>.

 

No Comments

Posted by: ...

Thursday, February 23rd 2012 12:54 am CST

 

No comments on file...