0

我有以下文件:

firstname=John
name=Smith
address=Som
 ewhere

如您所见,地址位于 2 行(第二行以空格开头)。

我必须将“好”输出(带有“address=Somewhere”)写入另一个文件。

这是我写的第一个脚本(有点复杂):

foreach $line (@fileIN) {
    if ($lastline eq "") {
        $lastline = $line;
    } else {
        if ($line =~/^\s/) {
            print $line;
            $line =~s/^\s//;
            $lastline =~s/\n//;
            $lastline = $lastline.$line;
        } else {
            print fileOUT $lastline;
            $lastline = $line;
        }
    }
}

$line =~/^\s/ => 这个正则表达式匹配 $line 中的空格,但不仅在开头。

我也尝试写一个简单的,但它也不起作用:

perl -pe 's/$\n^\s//' myfile
4

3 回答 3

1

比如像这样?

while (<DATA>) {
    chomp;
    print "\n" if /=/ and $. - 1; # do not insert empty line before the 1st line
    s/^\s+//;                     # remove leading whitespace
    print;
}
print "\n";                       # newline after the last line

__DATA__
firstname=John
name=Smith
address=Som
 ewhere
于 2012-05-30T09:56:38.173 回答
1

你似乎做了太多的工作。我会这样做:

my $full_line;
foreach my $line (@fileIN) {
    if ($line =~ /^\s+(.+)\Z/s){                   # if it is continuation
            my $continue = $1;                     # capture and
            $full_line =~ s/[\r\n]*\Z/$continue/s; # insert it instead last linebreak
    } else {                                       # if not
            if(defined $full_line){ print $full_line } # print last assembled line if any
            $full_line = $line;                    # and start assembling new
    }
}
if(defined $full_line){ print $full_line }         # when done, print last assembled line if any
于 2012-05-30T09:56:39.417 回答
0

仅检查我的解决方案 1 个正则表达式 :)

my $heredoc = <<END;
firstname=John
name=Smith
address=Som
 ewhere
END

$heredoc =~ s/(?:\n\s(\w+))/$1/sg;
print "$heredoc";`
于 2012-05-30T09:55:55.927 回答