replace substrings between patterns with sed GnuWin32

67 Views Asked by At

I want to try to find between patterns substrings then replace it

Source example text:

bbllaahh pattern1 blaah _SUBSTRING_ blah blaah
bbblah bbllaahh pattern1 blah blaah _SUBSTRING_ blahh  _SUBSTRING_ blaah blahh blah pattern2 blllah blaaah
blahh blllllah _SUBSTRING_ blaah pattern2 blluhhh

Expecting:

bbllaahh pattern1 blaah _SUBSTRING_ blah blaah
bbblah bbllaahh pattern1 blah blaah _REPLACE_ blahh  _REPLACE_ blaah blahh blah pattern2 blllah blaaah
blahh blllllah _SUBSTRING_ blaah pattern2 blluhhh

Patterns is could be different, and could be one or more in string. Source text not be changed except a substring replacement

I found example for unix:

sed '/pattern1/,/pattern2/' - doesn't work

sed '/pattern1/{s/_SUBSTRING_/_REPLACE_/}' - it's work but I am not sure whether working for pattern2 (' was replace " for win)

I was try to mixing but it doesn't work:

sed "/pattern1/,/pattern2/{s/_SUBSTRING_/_REPLACE_/}" - doesn't work pattern1

sed "/pattern1/,{s/_SUBSTRING_/_REPLACE_}/pattern2/" - doesn't work

Also _SUBSTRING_ could be instead a one of some special cheractors(like a ")

P.S.: This i do in window environment with sed GnuWin32

1

There are 1 best solutions below

2
sseLtaH On

This may work assuming you intend to find both pattern1 and pattern2 on the same line.

$ sed '/pattern1.*pattern2/s/_[^_]*_/_REPLACE_/g' input_file
bbllaahh pattern1 blaah _SUBSTRING_ blah blaah
bbblah bbllaahh pattern1 blah blaah _REPLACE_ blahh  _REPLACE_ blaah blahh blah pattern2 blllah blaaah
blahh blllllah _SUBSTRING_ blaah pattern2 blluhhh