Sang.P Sang.P - 6 months ago 10
Perl Question

Perl Script: sorting through log files.

Trying to write a script which opens a directory and reads bunch of multiple log files line by line and search for information such as example:
"Attendance = 0 " previously I have used

grep "Attendance ="
*
to search my information but trying to write a script to search for my information.
Need your help to finish this task.

#!/usr/bin/perl

use strict;
use warnings;
my $dir = '/path/';
opendir (DIR, $dir) or die $!;
while (my $file = readdir(DIR))
{
print "$file\n";
}
closedir(DIR);
exit 0;

Answer

I prefer to use File::Find::Rule for things like this. It preserves path information, and it's easy to use. Here's an example that does what you want.

use strict;
use warnings;

use File::Find::Rule;

my $dir = '/path/';
my $type = '*';

my @files = File::Find::Rule->file()
                            ->name($type)
                            ->in(($dir));

for my $file (@files){

    print "$file\n\n";

    open my $fh, '<', $file or die "can't open $file: $!";

    while (my $line = <$fh>){
        if ($line =~ /Attendance =/){
            print $line;
        }
    }
}