Shell编程-1:使用Linux shell脚本修改xml文件内容

我们的项目中有一个SkyCameraInfo.xml,在每次启动程序后需要手动修改这个xml文件里的内容,修改方式有两种:
1、使用sed命令

  • 新建shell脚本test.sh,赋予脚本可执行权限,脚本内容如下:
#!/bin/sh
if [ $# -ne 9 ];then
echo "usage argument 1:Version 2:Model 3: qId 4:qKey 5:mdQkey 6:SN 7:Mac 8:qKey2 9:mdQkey2"
exit 1
fi
Version=$1
Model=$2
qId=$3
qKey=$4
mdQkey=$5
SN=$6
Mac=$7
qKey2=$8
mdQkey2=$9
sed -i "s/.*<\/Version>/${Version}<\/Version>/;s/.*<\/Model>/${Model}<\/Model>/;s/.*<\/qId>/${qId}<\/qId>/;s/.*<\/qKey>/${qKey}<\/qKey>/;s/.*<\/mdQkey>/${mdQkey}<\/mdQkey>/;s/.*<\/SN>/${SN}<\/SN>/;s/.*<\/Mac>/${Mac}<\/Mac>/;s/.*<\/qKey2>/${qKey2}<\/qKey2>/;s/.*<\/mdQkey2>/${mdQkey2}<\/mdQkey2>/" SkyCameraInfo.xml
echo "The values of SkyCameraInfo.xml have changed."
  • 在执行shell脚本时候,添加9个参数,执行结束后xml文件中的内容被修改;
[root@localhost cfg]# ./test.sh 1 2 3 4 5 6 7 8 9
The values of SkyCameraInfo.xml have changed.
[root@localhost cfg]# cat SkyCameraInfo.xml 
<?xml version="1.0"?>
<SkyCameraInfo>	
   <Version>1</Version>
   <Model>2</Model>
   <qId>3</qId>         
   <qKey>4</qKey>	
   <mdQkey>5</mdQkey>
   <SN>6</SN>
   <Mac>7</Mac>
   <qKey2>8</qKey2>	
   <mdQkey2>9</mdQkey2>
</SkyCameraInfo>
[root@localhost cfg]# 

2、直接输出xml内容

  • shell脚本如下:
#!/bin/sh
if [ $# -ne 9 ];then
echo "usage argument 1:Version 2:Model 3: qId 4:qKey 5:mdQkey 6:SN 7:Mac 8:qKey2 9:mdQkey2"
exit 1
fi
Version=$1
Model=$2
qId=$3
qKey=$4
mdQkey=$5
SN=$6
Mac=$7
qKey2=$8
mdQkey2=$9
cat <<EOF >SkyCameraInfo.xml
<?xml version="1.0"?>
<SkyCameraInfo>	
	<Version>${Version}</Version>
	<Model>${Model}</Model>
	<qId>${qId}</qId>         
	<qKey>${qKey}</qKey>	
	<mdQkey>${mdQkey}</mdQkey>
	<SN>${SN}</SN>
	<Mac>${Mac}</Mac>
	<qKey2>${qKey2}</qKey2>	
	<mdQkey2>${mdQkey2}</mdQkey2>
</SkyCameraInfo>
EOF
echo "The values of SkyCameraInfo.xml have changed." 
  • 执行shell脚本;
[root@localhost cfg]# ./test1.sh 1 3 5 7 9 11 13 15 17
The values of SkyCameraInfo.xml have changed.
[root@localhost cfg]# cat SkyCameraInfo.xml 
<?xml version="1.0"?>
<SkyCameraInfo>	
	<Version>1</Version>
	<Model>3</Model>
	<qId>5</qId>         
	<qKey>7</qKey>	
	<mdQkey>9</mdQkey>
	<SN>11</SN>
	<Mac>13</Mac>
	<qKey2>15</qKey2>	
	<mdQkey2>17</mdQkey2>
</SkyCameraInfo>
[root@localhost cfg]#

参考文章:https://www.cnblogs.com/softidea/p/6039991.html

你可能感兴趣的:(#,Shell编程)