0

次のファイルがあります。

firstname=John
name=Smith
address=Som
 ewhere

ご覧のとおり、住所は 2 行に渡っています (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 に答える