I have a sizable nagios log file that I needed to parse somewhat quickly to return the most recent iteration of a particular message. I thought about implementing something in python, but I whipped up the below Perl script in about few minutes that does just what I need...
#!/usr/bin/perl -w
use strict;
use Tie::File;
use Fcntl;
# Log file to parse.
my $logfile = '/var/log/nagios/syslog-nagios';
my @msgs = ();
# Get the logfile in a data structure quietly
tie @msgs, 'Tie::File', $logfile,mode => O_RDONLY or die "Cannot access $logfile: $!
";
# Loop through reverse sorted list of messages.
foreach my $line (reverse(@msgs)) {
# print out the matched line..
print ((split(':',$line))[6]) && last if ($line =~ /TRAFFIC-INTERNET/);
}
I'm sure I could have done some fancy map() or grep() but the above does the job great, and does it quickly. So yeah, that's one of the reasons I still dig Perl.
