bash Shellscript 读取 XML 属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25508512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shellscript Read XML attribute value
提问by patel kavit
We want to read XML attributes from an XML file. Example of file content is as below:
我们想从 XML 文件中读取 XML 属性。文件内容示例如下:
<properties>
<property name="abc" value="15"/>
<property name="xyz" value="26"/>
</properties>
We want to read value (i.e. 15) for property "abc" using shell script.
Please suggest shell commands to achieve this.
我们想使用 shell 脚本读取属性“abc”的值(即 15)。
请建议 shell 命令来实现这一点。
回答by jaypal singh
You can use a proper XML parser like xmllint. If your version supports xpath, it will be very easy to grab specific values. If it doesn't support xpath, then you can use --shell
option like so:
您可以使用适当的 XML 解析器,如 xmllint。如果您的版本支持 xpath,那么获取特定值将非常容易。如果它不支持 xpath,那么您可以使用如下--shell
选项:
$ echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxml
/ > -------
value="15"
/ >
You can then use awk
or sed
to format and extract desired field from output.
然后,您可以使用awk
或sed
来格式化并从输出中提取所需的字段。
$ echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxmlfile | awk -F'[="]' '!/>/{print $(NF-1)}'
15
You can use command substitution to capture the output in a variable by saying:
您可以使用命令替换来捕获变量中的输出,如下所示:
$ myvar=$(echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxml | awk -F'[="]' '!/>/{print $(NF-1)}')
$ echo "$myvar"
15
Using anything else other than a xmlparser is prone to errors and will break easy.
使用除 xmlparser 以外的任何其他东西都容易出错并且容易出错。
回答by NeronLeVelu
quick and dirty
又快又脏
sed -n '/<Properties>/,\|</properties>| {
s/ *<property name="xyz" value="\([^"]*\)"\/>//p
}'
no xml check and based on your sample so assume same structure (one property name per line, ...)
没有 xml 检查并基于您的示例,因此假设相同的结构(每行一个属性名称,...)
posix version (--posix
for GNU sed)
posix 版本(--posix
用于 GNU sed)
回答by NeronLeVelu
sed -n '/<property name="abc"/s/.*value="\(.*\)"[^\n]*/\1/p' file
sed -n '/<property name="abc"/s/.*value="\(.*\)"[^\n]*/\1/p' file
Creates a hold pattern for the value then matches everything except for the newline to avoid printing the newline, it expects the value double quoted as per your example data.
为该值创建一个保持模式,然后匹配除换行符之外的所有内容以避免打印换行符,它期望根据您的示例数据双引号引用该值。
E.g.
<properties>
<property name="abc" value="15"/>
<property name="xyz" value="26"/>
</properties>
Output:
15
(Prior to edit: sed '/<property name="abc"/s/.*value="\(.*\)"[^\n]*/\1/' file
)
(在此之前编辑:sed '/<property name="abc"/s/.*value="\(.*\)"[^\n]*/\1/' file
)