【问题标题】:perl extract string after specific patternperl 在特定模式后提取字符串
【发布时间】:2021-02-02 13:50:43
【问题描述】:

我想提取(使用 perl)xxx(块之后的字符串:)和 prod(里程碑之后的字符串:)。字符串(在 Block: 和 Milestone: 之后)和空格数不是标准的。我只能使用底部命令 grep 整行:

use strict;
use warnings;

my $file = 'xxx.txt';
open my $fh, '<', $file or die "Could not open '$file' $!\n";
while (my $line = <$fh>){
    chomp $line;
#   my @stage_status = $line =~ /(\:.*)\s*$/;
my @stage_status = $line =~ /\b(Block)(\W+)(\w+)/;
    foreach my $stage_statuss (@stage_status){
        print "$stage_statuss\n";
    }
    }

文件中的行示例:

| Block:                   | xxx | Milestone:           | prod        |

【问题讨论】:

  • 根据下面的 cmets OP 正在 Perl/Grep 中尝试此代码并需要正则表达式帮助,因此它是相关标签。

标签: regex perl


【解决方案1】:

使用gnu grep 你可以做到:

grep -oP '\b(Block|Milestone)\W+\K\w+' file

xxx
prod

RexEx 详细信息:

  • \b;字边界
  • (Block|Milestone):匹配 BlackMilestone
  • \W+: 匹配 1+ 个非单词字符
  • \K: 重置匹配信息
  • \w+: 匹配 1+ 个单词字符

更新:

根据 OP 的编辑问题建议 perl 代码:

use strict;
use warnings;

my $file = 'xxx.txt';
open my $fh, '<', $file or die "Could not open '$file' $!\n";

while (my $line = <$fh>){
    chomp $line;
    print "checking: $line\n";
    my @stage_status = $line =~ /\b(?:Block|Milestone)\W+(\w+)/g;
    
    foreach my $stage_statuss (@stage_status){
       print "$stage_statuss\n";
    }
}

输出:

checking: | Block:                   | xxx | Milestone:           | prod        |
xxx
prod

【讨论】:

    【解决方案2】:

    您可以使用简单的awk 来完成此操作。通过设置适当的字段分隔符值,我们可以获得所需的值。只需将字段分隔符设置为管道,后跟空格或空格,然后在主程序检查条件中,如果第二个字段是块:然后打印第四个字段。

    awk -F'\\|[[:space:]]+|[[:space:]]+' '$2=="Block:"{print $4} $6=="Milestone:"{print $8}' Input_file
    


    第二个解决方案: 与我上面的第一个解决方案几乎相同的解决方案,唯一的事情是在这里为awk 制作一个字段分隔符。

    awk -F'([[:space:]]+)?\\|([[:space:]]+|$)' '$2=="Block:"{print $3} $4=="Milestone:"{print $5}' Input_file
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多