如何删除Perl文件中的模式之间的多行

时间:2016-03-28 16:24:27

标签: perl perl-module

问题>>我需要使用Perl删除“pattern1 / 2/3 {”和“}”之间提到的“要删除的行”的行! 感谢

Line 1 of code to keep
Line 2 of code to keep
}

pattern1 {
line to be deleted
line to be deleted

}

pattern2 {
line to be deleted
line to be deleted

}

pattern3 {
line to be deleted
line to be deleted

}

Line 3 of code to keep
Line 4 of code to keep
}

2 个答案:

答案 0 :(得分:0)

您可以将模式放入列表中,然后使用非贪婪匹配的正则表达式删除花括号括起来的行:

my @patterns = qw/
  pattern1
  pattern2
  pattern3
/;

foreach my $pattern (@patterns)
{
    $file_contents =~ s/^$pattern \{.*?\}/$pattern {\n}/ms;
}

答案 1 :(得分:0)

my @keywords = qw( pattern1 pattern2 pattern3 );

my $keywords_pat = "(?:\b(?:" . join("|", map quotemeta, @keywords) . ")\b)";

s/ $keywords_pat \s* \{ [^{}]* (?= \} )//xg;

s/ $keywords_pat \s* \{ \K ( [^{}]* (?: \{ (?1) \} [^{}]* )* ) (?= \} )//xg;

第二个版本处理嵌套的{...}