count number of xml element from linux shell count number of xml element from linux shell xml xml

count number of xml element from linux shell


The xml_grep tool does what you want - try the following:

xml_grep --count //elem example.xml

That utility is in the xml-twig-tools package on Debian / Ubuntu, and the documentation is here.


You can also use xmllint:

xmllint --xpath "count(//elem)" myfile.xml


DO NOT USE REGULAR EXPRESSIONS TO PARSE OR SCAN XML FILES

The mandatory disclaimer being fired, here's my solution:

xmllint --nocdata --format myfile.xml | grep -c '</elem>'

xmllint is part of libxml which is fairly common on many linux distros. This solution passes the following regex/XML traps:

  • spurious spaces (--format)
  • several closing tags on single line (--format)
  • CDATA sections (--nocdata)

However, you will be caught by nasty namespace declaration and defaults.