【问题标题】:Perl : convert new line to comma delimited between 2 repeating wordsPerl:将新行转换为在 2 个重复单词之间分隔的逗号
【发布时间】:2013-02-14 07:36:32
【问题描述】:

下面是单个列的输出,其中包含重复行,可以是正则表达式/拆分等的一部分。

我想将分组列转换为逗号分隔格式。有人可以帮我解决这个问题吗?

之前:

An instance of HostInfo
1=?  
2=?   
3=?    
4=?  
5=?
An instance of HostInfo
1=?
2=?
3=?
4=?
5=?

之后

1, 1=?, 2=?, 3=?, 4=?, 5=?

2, 1=?, 2=?, 3=?, 4=?, 5=? 

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    应该记住,Perl 中的 line 处理是 record 处理的一个实例。您可以将记录分隔符设置为适合您的数据。

    假设文件确实包含字符串“HostInfo 的实例”,您可以执行以下操作。

    你也可以设置你的记录分隔符:

    use English qw<$RS>;
    my $old_rs = $RS;
    local $RS = "An instance of HostInfo\n";
    

    然后你可以读取 那些 块中的文件。

    while ( <$input> ) { 
        chomp; # removes record separator
        next unless $_;
        ...
    }
    

    然后您可以将记录拆分成行并用逗号重新连接它们。所以... 是:

    say join( ', ', split $old_rs );
    

    【讨论】:

      【解决方案2】:

      这样的东西会起作用吗?

      use strict;
      use warnings;
      
      undef $/;
      
      my $output = <DATA>;
      
      my @parts = split /An instance of HostInfo/m, $output;
      
      my $ctr = 1;
      for my $part (@parts) {
        my @lines = split "\n", $part;
        @lines = grep {$_} @lines;
        next unless @lines;
        s/^\s+//g for @lines;
        s/\s+$//g for @lines;
        print $ctr++, ', ', join(", ", @lines),"\n";
      }
      
      __DATA__
      An instance of HostInfo
      1=?  
      2=?   
      3=?    
      4=?  
      5=?
      An instance of HostInfo
      1=?
      2=?
      3=?
      4=?
      5=?
      

      这会将您的示例输出读入单个字符串,将其拆分为“HostInfo 的实例”, 然后循环遍历这些线段,分割线,修剪它们,最后将它们重新连接在一起。

      【讨论】:

        【解决方案3】:

        尝试这样做:

        use strict; use warnings;
        
        my ($count, $hash);
        
        # magic diamond operator to read INPUT
        while (<>) {
            # removes newlines
            chomp;
            # if the line contains /An instance/
            # incrementing $count and skipping this line
            do{ $count++; next } if /An instance/;
            # else add current line in a reference to an array
            push @{ $hash->{$count} }, $_;
        }
        
        # iterating over "instances"
        foreach my $first_level (sort keys %$hash) {
            # finally we print the result by de-referencing the HASH ref
            print "$first_level ", join ", ", @{ $hash->{$first_level} }, "\n";
        }
        

        用法

        perl script.pl < input_file.txt
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-01-19
          • 2020-09-29
          • 1970-01-01
          • 2020-01-28
          • 2012-01-02
          • 1970-01-01
          • 2012-02-01
          • 2022-12-10
          相关资源
          最近更新 更多