perl-分割日志文件

时间:2018-11-07 14:41:44

标签: perl parsing split

我有一个日志文件:

Wed Oct 17 04:57:08 2018 : Resource = 'test1' cstep= 'titi' time =23.634s 
Wed Oct 17 04:57:50 2018 : Resource = 'test2' cstep= 'titi2' time =22.355s 
Wed Oct 17 04:58:41 2018 : Resource = 'test3' cstep= 'titi3' time =28.611s 
Wed Oct 17 04:58:46 2018 : Resource = 'test4' cstep= 'titi4' time =4.085s 

我只希望超过五秒钟的行:

Wed Oct 17 04:57:08 2018 : Resource = 'test1' cstep= 'titi' time =23.634s 
Wed Oct 17 04:57:50 2018 : Resource = 'test2' cstep= 'titi2' time =22.355s 
Wed Oct 17 04:58:41 2018 : Resource = 'test3' cstep= 'titi3' time =28.611s 

我的代码是:

open (FILE, 'logfile.txt');
while (<FILE>) {

($word1, $word2, $word3, $word4, $word5, $word6, $word7, $word8, $word9, $word10, $word11, $word12, $word13, $word14) = split(" ");
print " $word5-$word2-$word3 $word4 $word5 $word6 $word7 $word8 $word9 $word10 $word11 $word12 $word13 $word14 \n";

}
close (FILE);
exit;

3 个答案:

答案 0 :(得分:3)

我对其他答案进行了投票,但是我已经

$ perl -ne '/time =(\d+\.\d+)/; if($1>5){print $_;}' file1
Wed Oct 17 04:57:08 2018 : Resource = 'test1' cstep= 'titi' time =23.634s
Wed Oct 17 04:57:50 2018 : Resource = 'test2' cstep= 'titi2' time =22.355s
Wed Oct 17 04:58:41 2018 : Resource = 'test3' cstep= 'titi3' time =28.611s

答案 1 :(得分:2)

一些注意事项:

  1. 每当您发现自己写$variableN时,您可能都想要一个数组
  2. split的默认行为可以满足您的需求 3.您需要隔离感兴趣的字段,使其为数字,然后进行数字比较

代码:

use strict;
use warnings;

while (<DATA>) {
    my @fields = split;
    my $time = $fields[12];
    $time =~ s/[^\d.]//g; # remove everything except digits and dots

    next unless $time > 5;
    print; # or whatever
}

__DATA__
Wed Oct 17 04:57:08 2018 : Resource = 'test1' cstep= 'titi' time =23.634s
Wed Oct 17 04:57:50 2018 : Resource = 'test2' cstep= 'titi2' time =22.355s
Wed Oct 17 04:58:41 2018 : Resource = 'test3' cstep= 'titi3' time =28.611s
Wed Oct 17 04:58:46 2018 : Resource = 'test4' cstep= 'titi4' time =4.085s

答案 2 :(得分:1)

使用正则表达式匹配项从$ word13中提取时间并进行数字比较:

print " $word5-$word2-$word3 $word4 $word5 $word6 $word7 $word8 $word9 $word10 $word11 $word12 $word13 $word14 \n"
    if $word13 =~ /=([0-9.]+)/ and $1 > 5;