NA NA
NA NA

Reputation: 21

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

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

Upvotes: 1

Views: 1764

Answers (3)

NA NA
NA NA

Reputation: 21

I just did it with a small difference than what was suggested by Avinish Raj

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

Upvotes: 0

Sobrique
Sobrique

Reputation: 53478

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 ^$ e.g. a blank line.

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

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

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.

Upvotes: 2

Related Questions