我有以下格式的日志条目:
[29-Oct-2014 06:06:08] NOTICE: fpm is running, pid 104151
[29-Oct-2014 06:06:26] NOTICE: ready to handle connections
[29-Oct-2014 06:07:14] NOTICE: Terminating ...
[29-Oct-2014 06:07:14] NOTICE: exiting, bye-bye!
[31-Oct-2014 06:07:16] NOTICE: fpm is running, pid 104871
[31-Oct-2014 06:07:36] NOTICE: ready to handle connections
[31-Oct-2014 06:41:48] WARNING: [pool blah.com] child 105502 said into stderr: "NOTICE: PHP message: "
[31-Oct-2014 06:41:48] WARNING: [pool blah.com] child 105502 said into stderr: ""
我只想打印当前日期(31-Oct)的条目。
我一直在使用以下脚本,但我无法使用它:
use strict;
use Logwatch ':dates';
use Time::Local;
use POSIX qw(strftime);
my $date_format = '%d-%b-%Y %H:%M:%S';
my $filter = TimeFilter($date_format);
# we do not use any Date:: package (or strptime) as they are probably not available
my %month2num = ( Jan => 0, Feb => 1, Mar => 2, Apr => 3,
May => 4, Jun => 5, Jul => 6, Aug => 7,
Sep => 8, Oct => 9, Nov => 10, Dec => 11 );
# counting messages
while(<>) {
my $line = $_;
# skipping messages that are not within the requested range
next unless $line =~ /^\[($filter)\]/o;
$1 =~ /(\d+)-(\w+)-(\d+) (\d+):(\d+):(\d+)/;
my $time;
{
# timelocal is quite chatty
local $SIG{'__WARN__'} = sub {};
$time = timelocal($6, $5, $4, $1, $month2num{$2}, $3-1900);
}
}
我无法以我可以比较的格式提取日期,而且我不确定如何与当前日期进行比较。
答案 0 :(得分:2)
在perl中尝试以下代码:
<强>代码:强>
use strict;
use warnings;
use Time::Piece;
sub Dt_change
{
my $date_var=$_[0];
my $temp;
my %Month=(1 => 'Jan', 2 => 'Feb', 3 => 'Mar', 4 => 'Apr' , 5 => 'May' ,6 => 'Jun' , 7 => 'Jul', 8 => 'Aug' ,9 => 'Sep', 10 => 'Oct', 11 => 'Nov' , 12 => 'Dec');
if($date_var=~/^(\d+)\/0?(\d+)\/(\d+)$/)
{
my $day=$1;
my $year=$3;
my $month=$2;
$temp="$day" . "\-" . "$Month{$month}" . "\-" . "$year";
}
return $temp
}
my $logFile = $ARGV[0];
open my $fh,'<',$logFile or die "Couldn't open the log file $logFile:$!";
my $t = localtime;
my $date = $t -> dmy("/");
my $dateformat = "\[" . Dt_change($date);
my $fulldateformat = "\[" . Dt_change($date) . " " . $t -> hms . "\]";
$dateformat = quotemeta($dateformat);
print "Current date log entries:\n";
while(<$fh>)
{
if($_ =~ /$dateformat/is)
{
print "line number $. -> $_\n";
}
}
close($fh);
<强>用法:强>
perl filename.pl logfile
答案 1 :(得分:2)
您是否希望使用日期,过滤器或提取的日志条目执行更复杂的操作?使用日期和范围可能很棘手,但您似乎只是在寻找特定的日期字符串(即“当前日期”)。
perl -MTime::Piece -nE'$t=localtime; $tdate=$t->mday."-".$t->monname."-".$t->year;
say if m/^\[$tdate/' logs.txt
<强>输出:强>
[31-Oct-2014 06:07:16] NOTICE: fpm is running, pid 104871
[31-Oct-2014 06:07:36] NOTICE: ready to handle connections
[31-Oct-2014 06:41:48] WARNING: [pool blah.com] child 105502 said into stderr: "NOTICE: PHP message: "
[31-Oct-2014 06:41:48] WARNING: [pool blah.com] child 105502 said into stderr: ""