Boardman411
Boardman411

Reputation: 531

Using an awk command inside a Perl script

This may not be the best way to do the below, so any comments are appreciated.

I'm currently tailing a number of log files and outputting them to screen, so that I get a quick overview of the system.

What I would like to do is to highlight different messages [INFO], [WARN] and [ERROR]

The following syntax works fine on the command line, but fails when being called from Perl

system ("tail -n 5 $ArchiverLog | awk '{if ($4 ~ /DEBUG/)print "\033[1;33m"$0"\033[0m"; else if ($6 ~ /ERROR/) print "\033[1;31m"$0"\033[0m"; else print $0}'");

I believe Perl can do this

Should I read in the file line by line, match on the words and print to screen (I only want the last 10 lines). Is that a better option?

I've also seen reference to a2p, which is an awk to Perl translator. Would that be people's preferred choice?

Upvotes: 0

Views: 320

Answers (1)

harmic
harmic

Reputation: 30577

It seems crazy to use one powerful scripting language to call up another one so it can do something which the first one can do very well, so I would not persist with trying to call up awk from perl.

I have not had much experience with a2p, rather I tend to just translate such snippets by hand.

#!/usr/bin/perl
use strict;
foreach(`tail -n 5 $ArchiverLog`) {
        my @f = split;
        if ($f[4] =~ /DEBUG/) {
                print "\033[1;33m$_\033[0m";
        } elsif ($f[6] =~ /ERROR/) {
                print "\033[1;31m$_\033[0m";
        }  else {
                print $_;
        }
}

(Hard to say if the above is completely correct without some sample input to test it with).

As Borodin says in the comments a more elegant solution would be to use a Tailing module from CPAN rather than calling up tail as a subprocess. But for a quick tool that might be overkill.

NB: if $ArchiverLog comes from anywhere you don't have control of, remember to sanitise it, otherwise you are creating a nice security hole.

Upvotes: 1

Related Questions