zoukankan      html  css  js  c++  java
  • Linux Shell脚本读写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>
    复制代码

    需要修改里面的"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."
    复制代码

    测试下来调用$ ./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."
    复制代码

    思路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>
    复制代码

    思路4:用xsltproc

    很多Linux比如CentOS默认已安装xsltproc,所以用xslt可以很方便的把一个xml转换为另外一个xml。具体用法见这个网页。

    http://www.cnblogs.com/Mainz/archive/2012/09/22/2697955.html

  • 相关阅读:
    久未更 ~ 四之 —— Vsftpd出现 Failed to start Vsftpd ftp daemon错误
    久未更 ~ 三之 —— CardView简单记录
    久未更 ~ 二之 —— TextView 文字省略
    久未更 ~ 一之 —— 关于ToolBar
    【UVA1636】决斗Headshot
    【NOIP模拟】花园
    【UVA1262】Password
    【UVA10820】交表
    【UVA1635】哑元
    【UVA12716】GCD和XOR
  • 原文地址:https://www.cnblogs.com/softidea/p/6039991.html
Copyright © 2011-2022 走看看