【问题标题】:How do I split an output file into multiple blocks based on a pattern如何根据模式将输出文件拆分为多个块
【发布时间】:2013-08-04 01:32:33
【问题描述】:

我有一个包含以下内容的输出文件。我想根据“模式”将它分成块并存储在一个数组中。

Sample output:
100 pattern
line 1
line 2
line 3
101 pattern
line 4
102 pattern   
line 5
line 6
 ...   

nth 和 (n+1)th 出现的“模式”之间的内容是一个块:

Block 1:
100 pattern
line 1
line 2
line 3

Block 2:
101 pattern
line 4


Block 3:
102 pattern   
line 5
line 6

基本上我是在跨行搜索模式并将其间的内容存储到一个数组中。

请告诉我如何在 perl 中实现

【问题讨论】:

  • 将文件读入数组。将join数组的内容转换成单个字符串,然后split就你的模式。
  • 是否保证模式是基于 1 行的?你想让一个块成为数组的一个元素还是元素应该是行?你的模式的本质是什么?
  • 到目前为止你做了什么?究竟是什么难度?
  • 昨天做了这个工作,只是写一个算法。 :) while($line !~(/\d+ pattern/)){ read_in_array();} 等等。

标签: perl


【解决方案1】:

假设您的 pattern 是包含单词 pattern 的完整行(而普通行没有)并且您希望数组元素是整个块:

my @array;
my $i = 0;

for my $line ( <DATA> ) {
    $i++ if ( $line =~ /pattern/ );
    $array[$i] .= $line;
}

shift @array unless defined $array[0];  # if the first line matched the pattern

【讨论】:

    【解决方案2】:

    我知道你已经接受了一个答案,但我想通过读入数据并使用正则表达式来拆分它来展示你如何做到这一点。

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use 5.010;
    
    my $input = do { local $/; <DATA> };
    
    my @input = split /(?=\d+ pattern)/, $input;
    
    foreach (0 .. $#input) {
      say "Record $_ is: $input[$_]";
    }
    
    __DATA__
    100 pattern
    line 1
    line 2
    line 3
    101 pattern
    line 4
    102 pattern   
    line 5
    line 6
    

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 2011-12-25
      • 1970-01-01
      • 2011-12-09
      • 2017-01-02
      • 2017-09-05
      • 2022-09-27
      • 1970-01-01
      相关资源
      最近更新 更多