示例日志文件如下,
/home/ajoy/alert-dc/testlogs/host1013/harvester.log.20170410
/home/ajoy/alert-dc/testlogs/host1013/harvester.log.20170303
/home/ajoy/alert-dc/testlogs/host1013/harvester.log.20170406
/home/ajoy/alert-dc/testlogs/host1011/harvester.log.20170307
/home/ajoy/alert-dc/testlogs/host1011/harvester.log.20170306
/home/ajoy/alert-dc/testlogs/host1012/harvester.log.20170405
/home/ajoy/alert-dc/testlogs/host1011/harvester.log.20170304
/home/ajoy/alert-dc/testlogs/host1014/harvester.log.20170305
/home/ajoy/alert-dc/testlogs/host1011/harvester.log.20170410
/home/ajoy/alert-dc/testlogs/host1011/harvester.log.20170303
尝试将今天的日志文件推送到数组中。但它不会产生任何输出或任何错误。
我们的想法是将今天的日志加载到数组并处理每个文件以搜索"错误"如果有错误,则提供输出文件名,文件路径和错误(下面的示例一个),
HostName | Log Location | File Name | Error
host1011 | /home/ajoy/alert-dc/testlogs/host1011/ | harvester.log.20170410 | error: [Errno 110] Connection timed out
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
my @files;
my $logDir = "/home/ajoy/alert-dc/testlogs";
my $Date = `date +%Y%m%d`;
my $pattern = "harvester.log.$Date";
chomp($Date);
find(
sub { push @files, $File::Find::name unless -d; },
$logDir
);
foreach my $file (@files) {
if ($file =~ $pattern) { print "$file"; }
}
答案 0 :(得分:1)
在您的代码中只有一个小错误请在$date
之前选择$pattern
chomp($Date);
my $pattern = qr/harvester\.log\.$Date/;
或者扼杀$pattern
my $pattern = qr/harvester\.log\.$Date/;
chomp $pattern;
根据simbabque评论更好地使用Time::Piece模块,因此您的代码应该是
my $Date = localtime->ymd("") ;
最终的代码是
#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
use Time::Piece;
my @files;
my $logDir = "yourdir";
my $Date = localtime->ymd("") ;
my $pattern = qr/harvester\.log\.$Date/; #dot will match the any character except new line so we should escape it.
find(
sub { push @files, $File::Find::name unless -d; },
$logDir
);
foreach my $file (@files) {
if ($file =~ $pattern) { print "$file\n"; }
}
结合推送和日期检查
find(
sub { push @files, $File::Find::name if($File::Find::name =~m/$pattern/ and -f) },
$logDir
);