分析xml文件脚本

回复 收藏

文件内容如下:

<configuration>

    <artifactItems>

        <artifactItem>

           <groupId>zzz</groupId>

           <artifactId>aaa</artifactId>

        </artifactItem>

        <artifactItem>

           <groupId>xxx</groupId>

           <artifactId>yyy</artifactId>

        </artifactItem>

        <!-- </artifactItem> <groupId>some groupId</groupId> <

           <version>1.0.1.2.333.555</version> </artifactItem> -->

    </artifactItems>

</configuration>

写个脚本实现:

  1. 删除掉注释的行

  2. 把文件中的<artifactItems></artifactItems>内容过滤出来,并按这样的格式逐行输出 artifactItem:groupId:zzz

参考答案:(写了2小时,才弄完,太复杂了,也许有更好的方法)

#!/bin/bash

egrep -v '<!--|-->' 1.txt |tee 2.txt

grep -n 'artifactItem>' 2.txt |awk '{print $1}' |sed 's/://' > /tmp/line_number.txt

n=`wc -l /tmp/line_number.txt|awk '{print $1}'`

get_value(){

    sed -n "$1,$2"p 2.txt|awk -F '<' '{print $2}'|awk -F '>' '{print $1,$2}' > /tmp/value.txt

    nu=`wc -l /tmp/value.txt|awk '{print $1}'`

    for i in `seq 1 $nu`

    do

        x=`sed -n "$i"p /tmp/value.txt|awk '{print $1}'`

        y=`sed -n "$i"p /tmp/value.txt|awk '{print $2}'`

        echo artifactItem:$x:$y

    done

}

       

n2=$[$n/2]

for j in `seq 1 $n2`

do

    m1=$[$j*2-1]

    m2=$[$j*2]

    nu1=`sed -n "$m1"p /tmp/line_number.txt`

    nu2=`sed -n "$m2"p /tmp/line_number.txt`

    nu3=$[$nu1+1]

    nu4=$[$nu2-1]

    get_value $nu3 $nu4

done

2016-10-13 17:43 举报
已邀请:
0

Bokey

赞同来自:

sed '/<!--/,/-->/d' config.xml | sed -e '/^$/d' | sed -n '/<artifactItem>/,/<\/artifactItem>/p' | awk '{{printf"%s",$0}}'| sed s/[[:space:]]//g | sed -e "s/<groupId>/:/g" -e "s/<\/groupId><artifactId>/:/g" -e "s/<\/artifactId>/ /g" -e "s/<\/artifactItem>/\n/g"

回复帖子,请先登录注册

退出全屏模式 全屏模式 回复
评分
可选评分理由: