【问题标题】:Perl : Removing spaces in linesPerl:删除行中的空格
【发布时间】:2012-05-30 09:40:55
【问题描述】:

我有以下文件:

firstname=John
name=Smith
address=Som
 ewhere

如您所见,地址分两行(第二行以空格开头)。

我必须将“好的”输出(带有“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

【问题讨论】:

    标签: perl


    【解决方案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
    

    【讨论】:

    • 您可以像 choroba 一样使用 chomp,这将是更“类似 perl”的方式。
    【解决方案2】:

    比如这样?

    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
    

    【讨论】:

    • 如果文件是另一种格式怎么办?没有特别提到每行应该有一个 =,只是标识的行应该连接到上一个。
    • @OlegV.Volkov :好吧,没有完整的规范,只能猜测。
    • 一行可以包含多个 = 如你所说:)
    【解决方案3】:

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

    my $heredoc = <<END;
    firstname=John
    name=Smith
    address=Som
     ewhere
    END
    
    $heredoc =~ s/(?:\n\s(\w+))/$1/sg;
    print "$heredoc";`
    

    【讨论】:

    • 是否可以在变量中获取整个文件并对其进行替换?喜欢:open(FILE, "$myfile") || die "open: $!"; $FILE =~ s/(?:\n\s(\w+))/$1/sg; print $FILE;
    • @user1425653: my $file = do {local $/; &lt;$filehandle&gt;};
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多