用于文件中多个模式的 Grep [英] Grep for multiple patterns in a file
问题描述
我想计算我的 xml 文件中的 xml 节点数(grep 或以某种方式).
I'd like to count number of xml nodes in my xml file(grep or somehow).
....
<countryCode>GBR</countryCode>
<countryCode>USA</countryCode>
<countryCode>CAN</countryCode>
...
<countryCode>CAN</countryCode>
<someNode>USA</someNode>
<countryCode>CAN</countryCode>
<someNode>Otherone</someNode>
<countryCode>GBR</countryCode>
...
如何获得单个国家的数量,例如 CAN = 3、USA = 1、GBR = 2?如果不传入国家名称,可能还会有更多国家?
How to get count of individual countries like CAN = 3, USA = 1, GBR = 2? Without passing in the names of the countries there might be some more countries?
更新:
除了countrycode还有其他节点
There are other nodes beside countrycode
推荐答案
我的简单建议是使用 sort
和 uniq -c
My simple suggestion would be to use sort
and uniq -c
$ echo '<countryCode>GBR</countryCode>
<countryCode>USA</countryCode>
<countryCode>CAN</countryCode>
<countryCode>CAN</countryCode>
<countryCode>CAN</countryCode>
<countryCode>GBR</countryCode>' | sort | uniq -c
3 <countryCode>CAN</countryCode>
2 <countryCode>GBR</countryCode>
1 <countryCode>USA</countryCode>
您将在 grep
的输出中输入管道而不是 echo
.更强大的解决方案是使用 XPath.如果您的 XML 文件看起来像
Where you'd pipe in the output of your grep
instead of an echo
. A more robust solution would be to use XPath. If youre XML file looks like
<countries>
<countryCode>GBR</countryCode>
<countryCode>USA</countryCode>
<countryCode>CAN</countryCode>
<countryCode>CAN</countryCode>
<countryCode>CAN</countryCode>
<countryCode>GBR</countryCode>
</countries>
然后你可以使用:
$ xpath -q -e '/countries/countryCode/text()' countries.xml | sort | uniq -c
3 CAN
2 GBR
1 USA
我说它更健壮,因为使用专为解析平面文本而设计的工具在处理 XML 时本质上是不稳定的.根据原始 XML 文件的上下文,不同的 XPath 查询可能效果更好,它可以在任何地方匹配它们:
I say it's more robust because using tools designed for parsing flat text will be inherently flaky for dealing with XML. Depending on the context of the original XML file, a different XPath query might work better, which would match them anywhere:
$ xpath -q -e '//countryCode/text()' countries.xml | sort | uniq -c
3 CAN
2 GBR
1 USA
这篇关于用于文件中多个模式的 Grep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!