sed find and replace between two tags with multi l

2020-04-09 17:09发布

问题:

I want to find and replace a pattern where

text="
hold1
hold2 
<file option1='one'>
some text
some text 
...
... more data
</file>
this1
that1
"

pattern="<file.*</file>"

replacewith="<sometext>
value1
</sometext>"

output text="
hold1
hold2
<sometext> 
value1
</sometext>
this1
that1
"

P.S. These questions on Stackoverflow do not help. sed : printing lines between two words only when one of the line matches a third word or any pattern

Regex with sed, search across multiple lines

回答1:

Using sed you can try something like:

sed -e ':a;N;$!ba' -e 's#<file.*</file>#<sometext>\nvalue1\n</sometext>#' file

My sed is a little rusty but what we are doing here is using :a;N;$!ba we effectively create one long line in pattern space so that we can apply the second expression which does your substitution.

This will probably need GNU sed

Test:

$ cat file
hold1
hold2
<file option1='one'>
some text
some text
more data
</file>
this1
that1

$ sed -e ':a;N;$!ba' -e 's#<file.*</file>#<sometext>\nvalue1\n</sometext>#' file
hold1
hold2
<sometext>
value1
</sometext>
this1
that1


标签: linux sed