Reputation: 456
I would like to replace a string where the content is multiline. At each end of line, it can be a /n or \r\n, for the indentation, it can be tabulation or spaces, I don't know. I think the best way to find the string is to use pattern and replace it using sed. This is the content of the file :
<Element Blabla>
A content
A second content
A third content
</Element>
<Element TheSearchedElement>
A content
A second content
A third content
</Element>
<Element Blabla2>
A content
A second content
A third content
</Element>
I want to replace this block :
<Element TheSearchedElement>
A content
A second content
A third content
</Element>
By this block :
<Element TheSearchedElement>
A content
A second replaced
A third content
</Element>
I think I should create a variable oldPattern which contains the pattern to find and a variable newPattern which contains the new pattern to write. This is the content of my script :
$oldPattern='<Element TheSearchedElement>*A content*A second content*A third*content*</Element>'
$newPattern='<Element TheSearchedElement>/n/tA content/n/tA second replaced/n/tA third*content/n</Element>'
sed -e '/oldPattern/newPattern/' file.conf
The problem is I have an error at output : script.sh: 1: script.sh: =A contentA second contentA thirdcontent*: not found script.sh: 2: script.sh: =/n/tA content/n/tA second replaced/n/tA third*content/n: not found sed: -e expression n°1, char 14: useless chars after command
I hope you will can help me.
Upvotes: 0
Views: 180
Reputation: 133770
Could you please try following and let me know if this helps you.
awk '/<Element TheSearchedElement>/{print;getline;print;getline;print " A second replaced";next} 1' Input_file
In case you want to save output into same Input_file itself then do following(if you are happy with above command's results):
awk '/<Element TheSearchedElement>/{print;getline;print;getline;print " A second replaced";next} 1' Input_file > temp_file && mv temp_file Input_file
Upvotes: 1
Reputation: 212634
You don't need to do a multiline replacement, you just need to restrict your replacement to an address range:
sed '/^<Element TheSearchedElement>$/,\@^</Element>@{/second/s/content/repl/; }' input
Upvotes: 0