我有以下文件:
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 / =>这个正则表达式匹配$行中的空格,但不仅仅是在开头。
我也尝试写一个简单的但它也不起作用:
perl -pe 's/$\n^\s//' myfile
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
仅检查我的解决方案1 regexp:)
my $heredoc = <<END;
firstname=John
name=Smith
address=Som
ewhere
END
$heredoc =~ s/(?:\n\s(\w+))/$1/sg;
print "$heredoc";`