【问题标题】:perl - split a logfile [closed]perl - 拆分日志文件[关闭]
【发布时间】:2019-04-11 00:21:13
【问题描述】:

我有一个日志文件:

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;

【问题讨论】:

    标签: perl parsing split


    【解决方案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;
    

    【讨论】:

    • 或者我有 perl -ne '/time =(\d+\.\d+)/; if ($1>5){print $_;}' file1
    • 那个不行,有没有简单的代码
    • @EssexBoy:OP 似乎也在重组这条线。
    • @jack94:什么不起作用?我用你的输入数据测试了我的代码,它工作正常。
    • 我有消息语法错误,靠近“if $word13”
    【解决方案2】:

    我对其他答案投了赞成票,但我有

    $ 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
    

    【讨论】:

      【解决方案3】:

      几个注意事项:

      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
      

      【讨论】:

      • 感谢您的回答
      • 你知道如何将十月转换为 10 吗?
      • @jack94 有很多不同的方法可以做到这一点,但最好的方法是解析日期,然后按照你的意愿进行格式化。不过,这是一个单独的问题。
      猜你喜欢
      • 1970-01-01
      • 2012-10-02
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      相关资源
      最近更新 更多