在 bash 脚本中提取 XML 值 [英] Extract XML Value in bash script
本文介绍了在 bash 脚本中提取 XML 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从已作为变量读入我的脚本的 xml 文档中提取一个值.原始变量 $data 是:
I'm trying to extract a value from an xml document that has been read into my script as a variable. The original variable, $data, is:
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
</item>
我想提取第一个标题值,所以
and I wish to extract the first title value, so
15:54:57 - George:
我一直在使用 sed 命令:
I've been using the sed command:
title=$(sed -n -e 's/.*<title>(.*)</title>.*/1/p' <<< $data)
但这只会输出第二个标题值:
but this only outputs the second title value:
15:55:17 - Jerry:
有谁知道我做错了什么?谢谢!
Does anyone know what I have done wrong? Thanks!
推荐答案
正如 Charles Duffey 所说,XML 解析器是最好使用适当的 XML 解析工具进行解析.对于一次工作,以下应该有效.
As Charles Duffey has stated, XML parsers are best parsed with a proper XML parsing tools. For one time job the following should work.
grep -oPm1 "(?<=<title>)[^<]+"
测试:
$ echo "$data"
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
$ title=$(grep -oPm1 "(?<=<title>)[^<]+" <<< "$data")
$ echo "$title"
15:54:57 - George:
这篇关于在 bash 脚本中提取 XML 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文