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?
Решение
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.
Другие советы
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
Crude but effective:
sed '/<\/web-app>/i<error-page>\n<error-code>400</errorcode>\n<location>/error.html</location>\n</error-page>' filename
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
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