tattoo3d
tattoo3d

Reputation: 79

Creating a log file counter

New to the syntax of perl, trying to set up a counter that counts the number of time a failed password occurs from a log file, and than print out the total number to console. I get a lot of numbers printed to the screen, instead of just one total at the end. Any thoughts or directions would be helpful.

#!/usr/bin/perl
$count = 0;

open (MYFILE, 'auth.log');
while (my $line = <MYFILE>){
if ($line =~ /Failed password/){
$count++;
}
print $count;
#print "$line\n" if $line =~ /Failed password/;
#this was a print test to see if it would only print the failed password strings in the file.    
}
close (MYFILE);

Upvotes: 0

Views: 127

Answers (1)

Andy Lester
Andy Lester

Reputation: 93676

You need to move the print $count outside of the while loop.

You also should check the return code of the open our else you won't know if the file is missing or unopenable.

#!/usr/bin/perl

use warnings;
use strict;

my $count = 0;

open (my $fh, '<', 'auth.log') or die $!;
while (my $line = <$fh>){
    if ($line =~ /Failed password/){
        $count++;
    }
}
close $fh;
print $count;

Finally, here's another way to do it from the command line:

grep -c 'Failed password' auth.log

Upvotes: 4

Related Questions