问题描述
说我有以下XML:
<app-deployment>
<name>gr1</name>
<target>AdminServer</target>
<module-type>ear</module-type>
<source-path>/u01/app/wls1035_homes/wls1035_9999/grc864</source-path>
<security-dd-model>DDOnly</security-dd-model>
<staging-mode>stage</staging-mode>
</app-deployment>
<app-deployment>
<name>gr2</name>
<target>AdminServer</target>
<module-type>ear</module-type>
<source-path>/u01/app/wls1035_homes/wls1035_9999/grc864</source-path>
<security-dd-model>DDOnly</security-dd-model>
<staging-mode>nostage</staging-mode>
</app-deployment>
<app-deployment>
<name>gr3</name>
<target>AdminServer</target>
<module-type>ear</module-type>
<source-path>/u01/app/wls1035_homes/wls1035_9999/grc864</source-path>
<security-dd-model>DDOnly</security-dd-model>
</app-deployment>
我怎么能提取分期模式变量的值,说了名为GR2应用程序的部署?
how can i extract the value of the staging-mode tag, say for the app-deployment named gr2?
推荐答案
很多人(包括我自己),会告诉你,这是一个傻瓜的差事解析XML具有reg-EX基础的工具,那你应该使用专门的工具XML解析。 Xpath的应该适用于这一点,xmlstarlet就可以快速安装和使用包。
Many people (including myself), will tell you that it is a fools errand to parse xml with reg-ex based tools, and that you should use tools designed for xml parsing. Xpath should work for this, and xmlstarlet would be a package you could install and use quickly.
这是说,因为你承担你的数据会一直得到很好的形成,这是pretty容易使awk脚本搜索1模式,设置一个标志,寻找另一种模式,设置一个标志,等。而当你已经找到了最终目标,清理线路只提取所需的数据。
That said, given that you assume your data will always be well formed, it is pretty easy to make an awk script to search for 1 pattern, set a flag, look for another pattern, set a flag, etc. And when you have found the final target, cleanup the line to extract just the data you want.
set -- gr2
{ cat - <<-EOS
<app-deployment>
<name>gr2</name>
<target>AdminServer</target>
<module-type>ear</module-type>
<source-path>/u01/app/wls1035_homes/wls1035_9999/grc864</source-path>
<security-dd-model>DDOnly</security-dd-model>
<staging-mode>nostage</staging-mode>
</app-deployment>
EOS
} | awk '
/[<]app-deployment/{a=1}
a && /[<]name[>]'"$1"'/{n=1}
a && n && /[<]staging-mode[>]/{
sub(/[<]staging-mode[>]/,"", $0)
sub(/[<]\/staging-mode[>]/,"",$0)
print $0
exit
}
#dbg { print "a=" a "\tn=" n }
'
输出
nostage
的设置 - GR3
和 {...猫} |
是一个测试工具,你会包装这是一个shell脚本,即
The set -- gr3
and { cat ... } |
are a testing harness, you would wrap this is a shell script i.e.
cat printXMLarg.bash
#!/bin/bash
targ=$1; shift
awk '
/[<]app-deployment/{a=1}
a && /[<]name[>]'"${targ}"'/{n=1}
a && n && /[<]staging-mode[>]/{
sub(/[<]staging-mode[>]/,"", $0)
sub(/[<]\/staging-mode[>]/,"",$0)
print $0
exit
}
#dbg { print "a=" a "\tn=" n }
' "${@}"
和调用像
printXMLarg.bash gr3 *.xml
这第二部分是未经测试。让我知道,如果你有它的问题。
This 2nd part is untested. Let me know if you have problems with it.
我希望这有助于
这篇关于在shell脚本同一级别的其他标签的提取标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!