【问题标题】:Find replace across multiple lines in Perl?在 Perl 中跨多行查找替换?
【发布时间】:2014-09-01 00:35:52
【问题描述】:

有没有办法在 perl 中跨多行替换文件中以 START 开头并以 END 结尾的字符串实例?

即输入:

good
START
bad
bad
END
good

然后找到从START到END的范围,并替换为'replaced':

good
replaced
good

非常感谢。

【问题讨论】:

  • 是的。您需要一个多行正则表达式。模式的 m 修饰符将执行此操作。

标签: perl


【解决方案1】:

使用标志。类似于以下内容:

perl -ne '$inside = print "replaced\n" if /START/;
          print unless $inside;
          undef $inside if /END/' file

【讨论】:

  • 谢谢!有没有办法将它与 find 结合来更改文件?
  • @James: find . -type f ... -exec perl -i~ -ne ... {} \;
【解决方案2】:

你可以使用flip-flop .. operator:

perl -pe '$_ = $i == 1 ? "replaced$/" : "" if $i = /START/ .. /END/' file

$i 计数从STARTEND 的行数,或者在起始块之外时它保持错误值。

【讨论】:

    【解决方案3】:

    这是一个简单的 Perl 程序,它替换 START 和 END 之间的字符串(不区分大小写),如下面的代码所示:

    #!/usr/bin/perl
        use strict;
        use warnings;
        my $InFile = $ARGV[0];
        my $document = do {
            local $/ = undef;
            open my $fh, "<", $InFile or die "Error: Could Not Open File $InFile: $!";
          <$fh>;
        };
        $document =~ s/\bSTART\b.*?\bEND\b/replaced/isg;
        print $document;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-08
      • 2021-01-02
      相关资源
      最近更新 更多