Shell脚本从XML文件中提取值

时间:2016-07-15 15:52:10

标签: xml shell

可以请任何帮助我编写shell脚本来从下面的xml中找到值: -

<?xml version="1.0" encoding="UTF-8"?>
<log>
<logentry revision="36">
    <author>XYZ</author>
    <date>2014-07-15T14:47:18.328479Z</date>
    <paths>
        <path action="A" localPath="ABC" kind="unknown">/branches/ABC</path>
        <path action="A" localPath="ABC" kind="unknown">/branches/ABC</path>
        <path action="M" localPath="DEF" kind="unknown">/branches/CDF</path>
        <path action="M" localPath="DEF" kind="unknown">FRG</path>
    </paths>
    <msg>added</msg>
</logentry>
</log>

我想提取localPath的值,即“ABC”和“DEF”作为输出并写入一个文件。

2 个答案:

答案 0 :(得分:2)

使用支持XML的工具。例如:

$ xmllint --xpath '/log/logentry/paths/path/@localPath' file.xml 

输出:

 localPath="ABC" localPath="ABC" localPath="DEF" localPath="DEF"

您可以进一步处理

$ xmllint --xpath '/log/logentry/paths/path/@localPath' file.xml \
  | sed 's/"/\n/g;' \
  | grep -v '^ ' \
  | sort -u

获取

ABC
DEF

或使用xsh

open file.xml ;
$h := hash @localPath /log/logentry/paths/path ;
for { keys %$h } { echo (.) ; }

输出:

ABC
DEF

答案 1 :(得分:1)

......或者XMLStarlet

xmlstarlet sel -t -v /log/logentry/paths/path/@localPath -n

...发光:

ABC
ABC
DEF
DEF