Use grep to count number of occurs of a specific element in a single line XML text

For example, I can input.txt below, three lines of XML text, I want to count the number of id elements for each line:
<result><id>1</id><id>5</id><id>7</id></result>
<result><id>71</id></result>
<result><id>15</id><id>33</id></result>



I use grep -o:
cat input.txt | while read line; do echo $line | grep -o '<id>' | wc -l; done



The output should be:
3
1
2

No comments:

Post a Comment