1

I have an xml file I need to modify:

...
</web-app>

I want to add some text before this line. I've tried with the simple text and it works fine (I used /bin/ex):

s/<\/web-app/test &/

so I get what I want:

...
test </web-app>

But the real text I need to insert is:

<error-page>
<error-code>400</error-code>
<location>/error.html</location>
</error-page>

How should I deal with it? I've tried to create variable, like

STR='<error-page>
<error-code>400</error-code>
<location>/error.html</location>
</error-page>'

and use it

s/<\/web-app/"$STR" &/

but result is incorrect. Do I define var incorrectly? Is it possible to have such var with multinelines? How can I insert all these lines before ? Can it be done more simple with sed?

Francheska
  • 295
  • 1
  • 3
  • 11

5 Answers5

2

There are two issues. One, your string contains '/' characters, so you should use a different delimiter. Two, the newlines are problematic. You could do:

 $ STR2=$( echo "$STR" | sed 's/$/\\n/' | tr -d '\n' )
 $ sed "s@</web-app@$STR2 &@" 

The assignment to STR2 simply replaces all newlines with \n, and works in bash. In zsh, some word splitting is happening that makes STR2 the same as STR.

William Pursell
  • 204,365
  • 48
  • 270
  • 300
2

You can try

/bin/ex your.xml << EDIT
/<\/web-app>
i
<error-page>
<error-code>400</error-code>
<location>/error.html</location>
</error-page>
.
x
EDIT
pizza
  • 7,296
  • 1
  • 25
  • 22
1

Crude but effective:

sed '/<\/web-app>/i<error-page>\n<error-code>400</errorcode>\n<location>/error.html</location>\n</error-page>' filename
Beta
  • 96,650
  • 16
  • 149
  • 150
1

The problem is that STR contains newlines which ed will interpret that as commands. I would suggest putting the content of STR into a file and use r to read it in. For example:

echo -ne '/<\/web-app/-1r OTHER_FILE\nw\n' | ed -s FILE_TO_MODIFY
Thor
  • 45,082
  • 11
  • 119
  • 130
0

This might work for you:

STR='<error-page>\
<error-code>400</error-code>\
<location>/error.html</location>\
</error-page>'
echo -e '...\n</web-app>\n...' | sed '/<\/web-app>/i\'"$STR"
...
<error-page>
<error-code>400</error-code>
<location>/error.html</location>
</error-page>
</web-app>
...

To edit a file in place:

sed -i '/<\/web-app>/i\'"$STR" file
potong
  • 55,640
  • 6
  • 51
  • 83