在Perl中,只有在满足某些条件的情况下,如何才能将输入行与下一个输入行连接起来?

时间:2011-11-04 16:47:48

标签: perl

我的行

Line: foobar, foo
Line: webar, webar, we
Line: 
abcabc
abc
Line: 
xyzxyz
xyz

我想要做的是将它们加入一行:

Line: foobar, foo
Line: webar, webar, we
Line: abcabc, abc
Line: xyzxyz, xyz

2 个答案:

答案 0 :(得分:0)

一种方法是读取整个文件并在\nLine:上拆分,然后对数据进行一些修正。

use strict;
use warnings;
use Data::Dumper;

my $data = <<EOF;
Line: foobar, foo
Line: quxbar, quxbar, quxx
Line: 
abcabc
abc
EOF

$data =~ s/^Line: //;
my @lines = split("\nLine: ", $data);
s/\n/, /g for @lines;

print join "\n", map { "Line: $_" } @lines;

答案 1 :(得分:-1)

script.pl

#!/usr/bin/perl -w

my @lines;

while(<>) {
        chomp;

        if(m/^Line: /) {
                push @lines, $_;
        }
        else {
                if(length $lines[-1] == 6) {
                        $lines[-1] .= $_;
                }
                else {
                        $lines[-1] .= ", $_";
                }
        }
}

print "$_\n" for @lines;

将您的示例输入保存为文件文件并运行

cat file | perl script.pl