#!/usr/local/bin/perl # Copyright (c) 2013 by Jeremy Kister # Function: colorize logfile output # inspired/plucks from Jeff Weisberg's http://www.tcp4me.com/code/red # http://jeremy.kister.net/code/green # typical use: # ex: tail -f logfile | green -green something -blue else -blue foo -v junk # options specified first have higher priority use strict; use Getopt::Long; my %data; my %opt; my @expt; my $pri = 0; my %color = ( red => '1;31', blue => '1;34', purple => '1;35', cyan => '0;36', magenta => '1;35', yellow => '0;33', green => '0;32', gray => '0;37', ); unless( $ARGV[0] =~ /^-/ ){ # make a non-flagged argument auto-green push @{ $data{$pri++}{green} }, $ARGV[0]; shift @ARGV; } GetOptions( "v=s@" => \@expt, "i" => sub { $opt{i} = 'i' }, "replace|r=s@" => sub { shift; my ($s,$r) = split /\//, shift; push @{$opt{r}}, [ $s,$r ]; }, "red=s@" => sub { my $x = shift; push @{ $data{$pri++}{$x} }, shift; }, "blue=s@" => sub { my $x = shift; push @{ $data{$pri++}{$x} }, shift; }, "green=s@" => sub { my $x = shift; push @{ $data{$pri++}{$x} }, shift; }, "purple=s@" => sub { my $x = shift; push @{ $data{$pri++}{$x} }, shift; }, "magenta=s@"=> sub { my $x = shift; push @{ $data{$pri++}{$x} }, shift; }, "cyan=s@" => sub { my $x = shift; push @{ $data{$pri++}{$x} }, shift; }, "yellow=s@" => sub { my $x = shift; push @{ $data{$pri++}{$x} }, shift; }, "gray=s@" => sub { my $x = shift; push @{ $data{$pri++}{$x} }, shift; }, "help|?" => \&usage, ); $| = 1; LOOP: while(){ chop; for my $r ( @{$opt{r}} ){ s{$r->[0]}{$r->[1]}g; } for my $v (@expt){ next LOOP if /(?$opt{i})$v/ }; for my $p (sort keys %data){ my ($c) = keys %{$data{$p}}; for my $expr ( @{$data{$p}{$c}} ){ if ( /(?$opt{i})$expr/ ){ print "\e\[$color{$c}m$_\e\[0m\n"; next LOOP; } } } print "$_\n"; } sub usage { print STDERR < -yellow | -magenta | -cyan // -help do not print this message parameters may be specified multiple times ex: tail -f logfile | green -green something -blue else -blue foo -v junk options specified first have higher priority (echo testing | green -red test -green ting) EOH ; exit; }