Perl:多行匹配+为所有匹配的行添加前缀

Perl: Multiline match + Adding prefix to all matched lines

我是 Perl 初学者。我通常使用 "sed" 进行模式替换,但由于我需要在一个巨大的文件中注释掉一些多行部分,我想到使用 Perl 在多行搜索中更强大。

模式示例:

word1 {
    do not care1
    do not care2
    ...
} word2

预期输出:

#word1 {
#    do not care1
#    do not care2
#    ...
#} word2

我发现有关 perl 多行匹配的非常有用的问答,但我找不到任何 good/compact/easy 解决方案来为所有匹配的行(不仅仅是第一行)添加前缀。

现在,这是我写的代码:

perl -0777 -pe 's/(word1\s*{[^}]*\s*}\s*word2\s.*)/#/gm' 

但遗憾的是,它无法为所有匹配的行添加前缀 (#),如下所示:

#word1 {
    do not care1
    do not care2
    ...
} word2

你能帮忙吗?我希望代码仍然在 1 行中:)

使用范围运算符:

perl -pe 's/^/#/ if /word1\s*\{/ .. /\}\s*word2/'

这可能适合您 (GNU sed):

sed '/word1/,/word2/s/^/#/' file