简体   繁体   English

在perl中进行多行搜索和替换

[英]multiline search and replace in perl

I need some help in replacing a specific string using perl command, but the catch is that I need to replace this string only from the relevant tag and leave it as is in all other tags 在使用perl命令替换特定字符串时,我需要一些帮助,但要注意的是,我只需要从相关标签中替换此字符串,然后将其保留在所有其他标签中

my text file looks like this 我的文本文件看起来像这样

[myTag]
some values 
and more values
my_string_To_Replace
some more values

[anotherTag]
more values
my_string_To_Replace

I did try below but this command replaces last occurrence only

Thanks
perl -p -i'.backup' -e 'BEGIN{undef $/;} s/(\[myTag\].*)(my_string_To_Replace)(.*)/$1NewString$3/smg' myText.file
I'm expecting below results
[myTag]
some values 
and more values
NewString
some more values

[anotherTag]
more values
my_string_To_Replace

I would do like this, 我会这样

$ perl -00pe 's/\[myTag\].*?\Kmy_string_To_Replace/NewString/gs' file
[myTag]
some values 
and more values
NewString
some more values

[anotherTag]
more values
my_string_To_Replace

\\K discards previously matched characters and -00 enables paragraph slurp mode. \\K丢弃先前匹配的字符,并且-00启用段落slurp模式。

If you're ok without a one liner, this should do the trick. 如果没有一根内胆也没关系,这应该可以解决问题。 Using the record delimiter to detect if you're between [myTag] and ^$ eg a blank line. 使用记录定界符来检测您是否在[myTag]^$例如空白行。

use strict;
use warnings;

while ( <DATA> ) {
     if ( m/\[myTag\]/ .. /^$/ ) {
          s/my_string_To_Replace/some_other_text/;
     }
     print;        
}


__DATA__
[myTag]
some values 
and more values
my_string_To_Replace
some more values

[anotherTag]
more values
my_string_To_Replace

If you really want a 'one liner': 如果您真的想要“一个班轮”:

perl -p -i.bak -ne " if ( m/\[myTag\]/ .. /^$/ ) { s/my_string_To_Replace/some_other_text/; } " file.txt

我所做的只是与Avinish Raj所建议的稍有不同

perl -p -i'.backup' -e 'BEGIN{undef $/;} s/\[myTag\].*?\Kmy_string_To_Replace/NewString/gs' myFile

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM