Reputation: 436
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 a b c", 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?
Upvotes: 1
Views: 10694
Reputation: 58430
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."
Upvotes: 2
Reputation: 1474
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.
Upvotes: 0
Reputation: 798686
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>
Upvotes: 2
Reputation: 4478
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.
Upvotes: 0