我有一个如下所示的日志文件:
874899 root@commands to execute some files
Exit Status : 0
Exit time : Sun May 5 18:19:39 2013
874923 root@commands to execute some files
Exit Status : 2
Exit time : Sun May 5 18:19:42 2013
我有一个脚本,它查看一个模式并返回该匹配模式的下一行。脚本如下:
open(FH,'log.txt');
while ($line = <FH>) {
if ($line =~ /Exit Status/) {
print "$line";
print scalar <FH>;
}
}
我需要您的输入,我应该如何执行此操作,使其与Exit status
匹配(在本例中为2)并保存874923
行以及命令(在本例中)和Exit Time
作为两个独立的变量。
请更正我,因为我是perl的新手。
答案 0 :(得分:1)
您的代码可能是这样的:
use Data::Dumper;
open(FH,'inlog.txt');
my @stat;
my ($exitstatus, $exitstatusval, $exittime, $exittimeval, $exitcommands);
while ($line = <FH>) {
if ($line =~ m/\d+\s+.*@.*/) {
$exitcommands = $line;
}
if ($line =~ /Exit Status/) {
($exitstatus, $exitstatusval) = split(':',$line);
next;
}
if ($line =~ /Exit time/ and $exitstatusval == 2) {
($exittime, $exittimeval) = split(': ',$line);
push (@stat, {
commands => $exitcommands,
time => $exittimeval
});
}
}
print(Dumper(\@stat));
输出: 因此,这将为退出状态为2的条目打印'arrayref of hashrefs'
$VAR1 = [
{
'time' => 'Sun May 5 18:19:42 2013 ',
'commands' => '874923 root@commands to execute some files '
},
{
'time' => 'Sun May 4 18:19:42 2013',
'commands' => '874613 root@commands to execute some files '
}
];
答案 1 :(得分:0)
我就是这样做的......
use Data::Dumper;
open(FH,'<','log.txt');
my $current_log;
my @logs;
while (my $line = <FH>) {
if($line =~ /^\s*(\d+)\sroot\@(.*)/) {
if($current_log) {
push @logs,$current_log;
}
$current_log = {};
$current_log->{pid} = $1;
$current_log->{command} = $2;
}
if ($line =~ /Exit Status\s*:\s*(\d+)/) {
$current_log->{exit_status} = $1;
}
if($line =~ /Exit time\s*:\s*(.+)$/) {
$current_log->{exit_time} = $1;
}
}
if($current_log) {
push @logs,$current_log;
}
print Dumper \@logs;
那应该打印出以下内容:
$VAR1 = [
{
'exit_time' => 'Sun May 5 18:19:39 2013',
'pid' => '874899',
'exit_status' => '0',
'command' => 'commands to execute some files'
},
{
'exit_time' => 'Sun May 5 18:19:42 2013',
'pid' => '874923',
'exit_status' => '2',
'command' => 'commands to execute some files'
}
];
答案 2 :(得分:0)
借助哈希,这就是我使用的:
use Data::Dumper;
open(FH,'inlog.txt');
my %stat;
my ($exitstatus, $exitstatusval, $exittime, $exittimeval, $exitcommands);
while ($line = <FH>) {
if ($line =~ m/^(\d+)\s+.*@(.*)/) {
$exitcommands = $2;
$qbsid= $1;
}
if ($line =~ /Exit Status/) {
($exitstatus, $exitstatusval) = split(':',$line);
next;
}
if ($line =~ /Exit time/ and $exitstatusval == 2) {
($exittime, $exittimeval) = split(': ',$line);
$stat{$qbsid} = {
commands => $exitcommands,
time => $exittimeval
};
}
}
print(Dumper(\%stat));