在Linux下如何用Shell脚本读写XML?现有一个config.xml(转)
在Linux下如何用Shell脚本读写XML?现有一个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>
<config>
<server-ip>192.168.1.45</server-ip>
<server-port>1209</server-port>
<repository-temp-path>/home/john</repository-temp-path>
</config>
需要修改里面的"server-ip", "server-port" and "import-path",用Shell脚本的参数$1,$2,$3来写入。
思路1:用sed实现
首先想到的就是用sed正则匹配替换实现,写了一个shell脚本,是这样的:
#!/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 > config.xml
echo "Done."
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 > config.xml
echo "Done."
测试下来调用$ ./abc.sh 192.168.1.6 9909 \\/home\\/abc"是可以的,但环境变量不行,例如:$ ./abc.sh 192.168.1.6 9909 $HOME\\/abc",因为首先环境变量被解析了,所以存在反斜杠转义字符和sed替换冲突的问题。
用另外一个思路实现
另外一个思路是直接输出该xml的内容,测试下来很管用,使用很方便,不存在反斜杠转义字符的问题和环境变量的问题:
#!/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 >config.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."
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 >config.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."
思路3:用XMLStarlet
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>
<?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>
思路4:用xsltproc
很多Linux比如CentOS默认已安装xsltproc,所以用xslt可以很方便的把一个xml转换为另外一个xml。具体用法见这个网页。