在 shell 脚本中提取一个 XML 元素值

Extract an XML element value in shell script

我的 sample.xml 文件中有类似下面的内容,并且仅当 artifactIdapp1 因为我们将使用 shell 在给定文件中使用不同 artifactId 的多个相同标签集脚本。

<groupId>abc.app1</groupId>
<artifactId>app1</artifactId>
<packaging>pom</packaging>
<name>app1 ${version}</name>
<version>1.2.50</version>

我的最终输出如下所示,

variable1=1.2.50

请注意,我需要读取文件并提取该字符串。

小心 XML 模式提取。如果模式是层次结构,它可能会变得奇怪,您可能必须使用 XML 个专用库。

但是,在您的示例中,您可以结合使用 grep 和 cut 来提取您的模式:

cat $file | egrep '<version>' \
| cut '> -f 2 | cut '<' -f 1

要解析 xml 个文件,请使用 xml 个解析器。

xmllint --xpath 'string(//version)' -