Search code examples
bashshellsedex

Trying to modify file with shell script - with /bin/ex


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?


Solution

  • 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.