Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 20th, 2012  |  syntax: None  |  size: 0.95 KB  |  hits: 60  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. count number of xml element from linux shell
  2. <elements>
  3. <elem>
  4. ....bunch of other elements
  5. </elem>
  6. </elements>
  7.        
  8. awk 'BEGIN{
  9.     totalelem=0
  10.     totalendelem=0
  11. }
  12. /<elem>/{
  13.     m = split($0,a,"<elem>") # or m = gsub(/<elem>/,"")
  14.     totalelem+=m-1
  15. }
  16. /</elem>/{
  17.     m = split($0,b,"</elem>") # or m = gsub("</elem>","")
  18.     totalendelem+=m-1
  19. }
  20. END{
  21.     print "Total elem tags: " totalelem
  22.     print "Total end elem tags: " totalendelem
  23.     # if you want to make sure each elem tag is enclosed  by corresponding end elem tag
  24.     if ( totalelem == totalendelem ){
  25.         print "Equal start and end tags"
  26.     }
  27. }
  28. ' file
  29.        
  30. xml_grep --count //elem example.xml
  31.        
  32. <elements>
  33. <elem>....bunch of other elements</elem><elem>....bunch of other elements</elem>
  34. <elem>
  35. ....bunch of other elements
  36. ....bunch of other elements
  37. </elem>
  38. </elements>
  39.        
  40. echo $(($(xmlstarlet sel -t -m //elem -n YOURFILE.xml | wc -l)-1))
  41.        
  42. xmllint --nocdata --format myfile.xml | grep -c '</elem>'