【问题标题】:Perl regex - extract two sections per linePerl 正则表达式 - 每行提取两个部分
【发布时间】:2015-12-29 11:28:51
【问题描述】:

我正在尝试从命令行使用 Perl 和正则表达式从日志文件中提取信息:

cat file_1 | perl -ne 'print if s/(2015-09-..) .*for (.\d+,\d)/\1/'
2015-09-02 20:03:05,037 INFO  [ajp-bio-10.247.96.38-27032-exec-92] (RegisterOnlineAction:474) - REGISTRATION for [735078385,1]: Perform Action.
2015-09-02 20:26:41,383 INFO  [ajp-bio-10.247.96.39-27002-exec-66] (RegisterOnlineAction:474) - REGISTRATION for [724314312,1]: Perform Action.
2015-09-02 21:09:47,890 INFO  [ajp-bio-10.247.96.38-27002-exec-65] (RegisterOnlineAction:474) - REGISTRATION for [328057138,1]: Perform Bill.

但我没有得到我需要的输出。

我需要的是:

2015-09-02 735078385,1
2015-09-02 724314312,1
2015-09-02 328057138,1

'print if s/text/text/' 进行搜索和替换,可能不是最好的方法。但是有什么方法可以每行选择多个部分并将它们输出。

【问题讨论】:

  • 将您的正则表达式更新为\[(.\d+,\d)\] 以匹配方括号。
  • 这给了我与初始命令类似的输出:cat file_1 | perl -ne 'print if s/(2015-09-..) .*for [(.\d+,\d)]/\1/' 2015-09-02: 执行操作。 2015-09-02:执行操作。 2015-09-02:执行法案。

标签: regex perl shell


【解决方案1】:

也匹配方括号:

 < file_1 perl -ne '/(2015-09-..).*for (\[[0-9,]+\])/ and print "$1 $2\n"'

【讨论】:

  • 这就是它,比你好多了
【解决方案2】:

这是我在 shell 中使用 egrepawktr

的版本
egrep '(2015-09-..) .*for (.[0-9]+,[0-9])' /tmp/xx | awk '{print $1,$9}' | tr -s '[]:' ' '

【讨论】:

    【解决方案3】:

    拆分和转换怎么样?

    #!/usr/bin/env perl 
    use strict;
    use warnings; 
    
    while ( <> ) {
        my @stuff = split /,/;
        $stuff[2] =~ s/\].*//;
        print "$stuff[0],$stuff[2]";
    }
    

    或者如果你在一行之后:

    perl -ne 'print join ( ",", (map { s/\].*//g; $_ } split /,/)[0,2] );'
    

    【讨论】:

      【解决方案4】:

      你可以像这样使用 oneliner 并从命令行运行它:

      perl -lnae '$F[8] =~ /(\d+,\d+)/ and print join " ", $F[0], $1' file.log  
      

      1) 键 -n 循环遍历输入文件 (file.log) 中的所有行。

      2) 然后键 -a 用空格分割每一行并将非空值放入 @F 数组中。所以日期将在$F[0] 中,而像“[735078385,1]:”这样的值将在$F[8] 中。我使用正则表达式/(\d+,\d+)/$F[8] 中提取正确的值(不带方括号和冒号)并将其保存到$1 变量中。

      【讨论】:

        猜你喜欢
        • 2015-10-28
        • 2015-12-25
        • 2013-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多