2013-06-04 106 views
0

我试图从日志中提取进程中所用的时间。perl正则表达式:使用正则表达式捕获

例如日志包含(相关行):

Time for search copy=15 s. 
Time for content copy=45 s. 
Time for unzip reply=20 s. 

上述线侧有许多其他线在日志中,其不是必需的。有几种作业可以生成这样的日志(日志名称是process.out),所以我们有一个Job_name作为每个作业的标识符。 我正在使用散列来读取特定作业的日志。下面是代码:

#!/usr/bin/perl 

use strict; 
use warnings; 
use File::Basename; 

my %Log_name =(); 
my %File_name =(); 
my %filetoread =(); 
my %filetoreadStrings =(); 
my @ftr  =(); 
my @reply =(); 
my @content =(); 
my @search =(); 
my %Reply =(); 
my %Search =(); 
my %Content =(); 
my $curr_dir=`pwd`; 
chop($curr_dir); 

my $Log_name = "ABC-DEF"; 
my $File_name=<$curr_dir/p*.out>; 
my $filetoread = basename ($File_name); 
my $filetoreadStrings=`strings $filetoread | egrep "(Time for)"`; 
@ftr = split('\n', $filetoreadStrings); 
chomp (@ftr); 


for (my $count = 0; $count < 6; $count++) #The lines are repeated 6 times except for the "search copy" line which is repeated twice 
{ 
$reply[$count] = (grep /Time for unzip reply/, @ftr)[$count]; 
$content[$count] = (grep /Time for content copy/, @ftr)[$count]; 
$search[$count] = (grep /Time for search copy/, @ftr)[$count]; 
if (defined $reply[$count]) 
{ 
($Reply{$Log_name}) = $reply[$count] =~ /Time for unzip reply=(\d+) s./; 

printf "$Reply{$Log_name}\n"; 
} 
    if (defined $content[$count]) { 
($Content{$Log_name})=$content[$count]=~/Time for content copy=(\d+) s./; 

printf "$Content{$Log_name}\n"; 
    } 
    if (defined $search[$count]) { 
    ($Search{$Log_name}) = $search[$count] =~ /Time for search copy=(\d+) s./; 

    printf "$Search{$Log_name}\n"; 
    } 

} 

上述代码的输出是:

Use of uninitialized value in concatenation (.) or string at new_try_loop.pl line 46. 

上述输出对应于每个printf语句的。实际上我需要将这些时间值加起来来计算总时间,而且我没有在代码中显示,因为重要的是首先获得“时间”。

这里需要做什么?让我知道是否需要其他信息。

最初,我没有使用for循环,并且此代码正在工作。例如,

$reply1 = (grep /Time for unzip reply/, @ftr)[0]; 
$Reply1{$Log_name}) = $reply1 =~ /Time for unzip reply=(\d+) s./; 
$reply2 = (grep /Time for unzip reply/, @ftr)[1]; 
$Reply2{$Log_name}) = $reply1 =~ /Time for unzip reply=(\d+) s./; 
$reply3 = (grep /Time for unzip reply/, @ftr)[2]; 
$Reply3{$Log_name}) = $reply1 =~ /Time for unzip reply=(\d+) s./; 
.......... and so on 

以类似的方式,我将值存储在$ Content {$ Log_name}和$ Search {$ Log_name}中。我正在获取这些变量中捕获的正则表达式,并在稍后添加它们。我正在使用for循环来优化这个。

回答

0

节这样

if (defined $reply[$count]) 
{ 
($Reply{$Log_name}) = $reply[$count] =~ /Time for unzip reply=(\d+) s./; 

printf "$Reply{$Log_name}\n"; 
} 

成为

if (defined $reply[$count] && ($reply[$count] =~ /Time for unzip reply=(\d+) s./)) 
{ 
($Reply{$Log_name}) = $1 
print "$1\n"; 
} 

我假设你的一些数据的匹配/Time for unzip reply/但不/Time for unzip reply=(\d+) s./

+0

谢谢!这是按照我的要求工作的,我在做了一些修改后使用了你的代码。而且你的假设是正确的:)。 – Freeman