
Untitled
By: a guest on
Jun 20th, 2012 | syntax:
None | size: 0.95 KB | hits: 60 | expires: Never
count number of xml element from linux shell
<elements>
<elem>
....bunch of other elements
</elem>
</elements>
awk 'BEGIN{
totalelem=0
totalendelem=0
}
/<elem>/{
m = split($0,a,"<elem>") # or m = gsub(/<elem>/,"")
totalelem+=m-1
}
/</elem>/{
m = split($0,b,"</elem>") # or m = gsub("</elem>","")
totalendelem+=m-1
}
END{
print "Total elem tags: " totalelem
print "Total end elem tags: " totalendelem
# if you want to make sure each elem tag is enclosed by corresponding end elem tag
if ( totalelem == totalendelem ){
print "Equal start and end tags"
}
}
' file
xml_grep --count //elem example.xml
<elements>
<elem>....bunch of other elements</elem><elem>....bunch of other elements</elem>
<elem>
....bunch of other elements
....bunch of other elements
</elem>
</elements>
echo $(($(xmlstarlet sel -t -m //elem -n YOURFILE.xml | wc -l)-1))
xmllint --nocdata --format myfile.xml | grep -c '</elem>'