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>
...
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?
Update:
There are other nodes beside countrycode
If your file is set up as you had shown to us,
awk
can do it like:If there are more than one
<countryCode>
tag on a line, you can still set up some pipe to make it into one line, e.g.:Note if the
<countryCode>
spans to multiple lines, it does not work as expected.Anyway, I'd recommend to use
xpath
for this kind of task (perl
'sxml::xpath
module has a CLI utility for this.grep
can give a total count, but it doesn't do a per-pattern; for that you should useuniq -c
:If you want to get rid of the empty lines and tags, add
sed
:To delete lines that don't have a country code, add another command to
sed
: