简体   繁体   中英

Shell script to find & replace value in xml

I have a xml config file called config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<config>
   <server-ip>192.168.1.45</server-ip>
   <server-port>1209</server-port>
   <repository-temp-path>/home/john</repository-temp-path>
</config>

I have a shell script to configure the values of "server-ip", "server-port" and "import-path" with $1,$2,$3:

#!/bin/sh
if [ $# -ne 3 ];then
echo "usage: argument 1:IP_Address 2:Server_PORT 3:Temp_PATH"
exit 1
fi
IP=$1
PORT=$2
DIRT=$3

echo "Change values in config.xml..."

sed "s/<server-ip>.*<\/server-ip>/<server-ip>$IP<\/server-ip>/;s/<server-port>.*<\/server-port>/<server-port>$PORT<\/server-port>/;s/<repository-temp-path>.*<\/repository-temp-path>/<repository-temp-path>$DIRT<\/repository-temp-path>/" config.xml > config2.xml

echo "Done."

But it only works for the " $ ./abc.sh abc ", and not work for " $ ./abc.sh 192.168.1.6 9909 /home/bbb ".... can you help to get it working and end up with a better solution?

XML + shell = XMLStarlet

$ xmlstarlet ed -u /config/server-ip -v 192.168.1.6 -u /config/server-port -v 9909 -u /config/repository-temp-path -v /home/bbb input.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
  <server-ip>192.168.1.6</server-ip>
  <server-port>9909</server-port>
  <repository-temp-path>/home/bbb</repository-temp-path>
</config>

This might work for you:

#!/bin/sh
if [ $# -ne 3 ];then
echo "usage: argument 1:IP_Address 2:Server_PORT 3:Temp_PATH"
exit 1
fi
IP=$1
PORT=$2
DIRT=$3

echo "Change values in config.xml..."

cat <<EOF >config2.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
   <server-ip>${IP}</server-ip>
   <server-port>${PORT}</server-port>
   <repository-temp-path>${DIRT}</repository-temp-path>
</config>
EOF  

echo "Done."

The slashes in /home/bbb are throwing it off (I assume you ran into the same problem I did, since you didn't say why it ain't working).

You could escape the slashes first if you're confident of the input. Might be better to fire up perl, ruby, etc for this.

I would really suggest using something like xmlstarlet. (http://xmlstar.sourceforge.net/) To the original question, the periods and '/' are getting substituted into the sed command. They need to be escaped but you can't possibly know if they are going to exist or not. I will look a little more into it, but use xmlstarlet, or another tool besides sed meant for xml, if you can.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM