JVK*_*JVK 3 bash shell xml-parsing xmllint
在shell脚本中,我有一个xml文件作为p.xml,如下所示,我想解析它并获取两个数组中的值.我正在尝试使用xmllint,但无法获得所需的数据.
<?xml version="1.0" encoding="UTF-8"?>
<Share_Collection>
<Share id="data/Backup" resource-id="data/Backup" resource-type="SimpleShare" share-name="Backup" protocols="cifs,afp"/>
<Share id="data/Documents" resource-id="data/Documents" resource-type="SimpleShare" share-name="Documents" protocols="cifs,afp"/>
<Share id="data/Music" resource-id="data/Music" resource-type="SimpleShare" share-name="Music" protocols="cifs,afp"/>
<Share id="data/OwnCloud" resource-id="data/OwnCloud" resource-type="SimpleShare" share-name="OwnCloud" protocols="cifs,afp"/>
<Share id="data/Pictures" resource-id="data/Pictures" resource-type="SimpleShare" share-name="Pictures" protocols="cifs,afp"/>
<Share id="data/Videos" resource-id="data/Videos" resource-type="SimpleShare" share-name="Videos" protocols="cifs,afp"/>
</Share_Collection>
Run Code Online (Sandbox Code Playgroud)
我想得到一个数组所有共享ID和一个包含共享名称的数组.所以两个数组就像
share-ids-array = ["data/Backup", "data/Documents", "data/Music", "data/OwnCloud", "data/Pictures", "data/Videos"]
share-names-array = ["Backup", "Documents", "Music", "OwnCloud", "Pictures", "Videos"]
Run Code Online (Sandbox Code Playgroud)
我开始如下:
xmllint --xpath '//Share/@id' p.xml
xmllint --xpath '//Share/@share-name' p.xml
Run Code Online (Sandbox Code Playgroud)
这给了我
id="data/Backup"
id="data/Documents" id="data/Music" id="data/OwnCloud" id="data/Pictures" id="data/Videos"
Run Code Online (Sandbox Code Playgroud)
任何建立这两个阵列的帮助将不胜感激.
这是一个使用grep(和tr)的解决方案... sed或awk是其他替代方案.顺便说一句,你不能在bash中的变量名中使用连字符.
share_ids=($( xmllint --xpath '//Share/@id' p.xml | grep -Po '".*?"' | tr -d \" ))
share_names=($( xmllint --xpath '//Share/@share-name' p.xml | grep -Po '".*?"' | tr -d \" ))
Run Code Online (Sandbox Code Playgroud)
例:
$ echo ${share_names[@]}
Backup Documents Music OwnCloud Pictures Videos
Run Code Online (Sandbox Code Playgroud)
但是,使用xmlstarlet可能更好:
share_names=($( xmlstarlet sel -T -t -m '//Share/@share-name' -v '.' -n p.xml ))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5547 次 |
最近记录: |