Variable

從 XML 標籤設置 bash 變數

  • February 13, 2019

我有以下 xml 文件

<root> <deviceID>IO238470374109730497</devicdeID> <KeyValuePairs> <KeyValuePair> <BASE-URL>site.com</BASE-URL> <Key>329482</Key> <Value>23094</Value> </KeyValuePair> <KeyValuePair> <BASE-URL>anothersite.com</BASE-URL> <Key>36657</Key> <Value>1233</Value> </KeyValuePair> <KeyValuePair> <BASE-URL>yetanothsite.com</BASE-URL> <Key>3345</Key> <Value>65087</Value> </KeyValuePair> </KeyValuePairs> </root>

我想提取所有的值<BASE-URL>,<Key>,<Value>並將它們設置為 bash 腳本中的變數。

執行此命令將僅列印值

xmlstarlet sel -t -m '//KeyValuePair' -v 'concat(BASE-URL," ", Key, " ", Value, " ")' -nl file.xml

如何將這些值設置為變數?

我想從 xml 中提取值並將它們發送到這樣的變數<BASE-URL>to $base_url<Key>to$key<Value>to $value

假設值從不包含空格,您可以執行以下操作:

xmlstarlet sel -t -m '//KeyValuePair' -v 'concat(BASE-URL," ", Key, " ", Value, " ")' -nl file.xml | while read base_url key value
do
   echo "base_url=$base_url key=$key value=$value"
done

引用自:https://unix.stackexchange.com/questions/500401