user744251
user744251

Reputation:

sed find and replace between two tags with multi line

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

Upvotes: 4

Views: 2899

Answers (1)

jaypal singh
jaypal singh

Reputation: 77105

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

Upvotes: 6

Related Questions