Bash 尝试使用shell脚本修改文件-使用/bin/ex

Bash 尝试使用shell脚本修改文件-使用/bin/ex,bash,shell,sed,ex,Bash,Shell,Sed,Ex,我有一个xml文件需要修改: ... </web-app> 。。。 我想在这行之前添加一些文本。我尝试过简单的文本,效果很好(我使用了/bin/ex): s/原油但有效: sed '/<\/web-app>/i<error-page>\n<error-code>400</errorcode>\n<location>/error.html</location>\n</error-page>' fil

我有一个xml文件需要修改:

...
</web-app>
。。。
我想在这行之前添加一些文本。我尝试过简单的文本,效果很好(我使用了/bin/ex):

s/原油但有效:

sed '/<\/web-app>/i<error-page>\n<error-code>400</errorcode>\n<location>/error.html</location>\n</error-page>' filename
sed'//i\n400\n/error.html\n“文件名
原油但有效:

sed '/<\/web-app>/i<error-page>\n<error-code>400</errorcode>\n<location>/error.html</location>\n</error-page>' filename
sed'//i\n400\n/error.html\n“文件名

有两个问题。首先,字符串包含“/”字符,因此应该使用不同的分隔符。第二,新词有问题。你可以做:

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

$sed“s@有两个问题。第一,字符串包含“/”字符,因此您应该使用不同的分隔符。第二,换行符有问题。您可以执行以下操作:

 $ STR2=$( echo "$STR" | sed 's/$/\\n/' | tr -d '\n' )
 $ sed "s@</web-app@$STR2 &@" 
$STR2=$(echo“$STR”| sed's/$/\\n/'| tr-d'\n')
$sed“s@你可以试试

/bin/ex your.xml << EDIT
/<\/web-app>
i
<error-page>
<error-code>400</error-code>
<location>/error.html</location>
</error-page>
.
x
EDIT
/bin/ex your.xml您可以试试

/bin/ex your.xml << EDIT
/<\/web-app>
i
<error-page>
<error-code>400</error-code>
<location>/error.html</location>
</error-page>
.
x
EDIT

/bin/ex your.xml问题在于
STR
包含新行,这些新行将
ed
解释为命令。我建议将
STR
的内容放入一个文件中,并使用
r
将其读入。例如:

echo -ne '/<\/web-app/-1r OTHER_FILE\nw\n' | ed -s FILE_TO_MODIFY

echo-ne'/问题在于
STR
包含新行,而
ed
将其解释为命令。我建议将
STR
的内容放入一个文件中,并使用
r
将其读入。例如:

echo -ne '/<\/web-app/-1r OTHER_FILE\nw\n' | ed -s FILE_TO_MODIFY

echo-ne'/这可能适合您:

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>
...
STR='1〕\
400\
/error.html\
'
echo-e'..\n\n...| sed'//i\'“$STR”
...
400
/error.html
...
要在位编辑文件,请执行以下操作:

sed -i '/<\/web-app>/i\'"$STR" file
sed-i'//i\'“$STR”文件

这可能适合您:

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>
...
STR='1〕\
400\
/error.html\
'
echo-e'..\n\n...| sed'//i\'“$STR”
...
400
/error.html
...
要在位编辑文件,请执行以下操作:

sed -i '/<\/web-app>/i\'"$STR" file
sed-i'//i\'“$STR”文件
使用“.”的目的是什么?退出文本输入模式?使用“.”的目的是什么?退出文本输入模式?