m_s
m_s

Reputation: 37

How to receive the number of specific entries from XML-file?

XML-file contains departments and users from a company next to some other comments. The number of users vary, also the last comment after the user:

 <department="marketing" id="983343" >
   <options="yes" />
   <prefix="m" />
   <country="de" />
   <user="MaierM" />
        .
        .
        .
   <user="SchulzP" />
   <success="yes" />
 </department>
 <department="sales" id="353934" >
   <options="yes" />
   <prefix="s" />
   <country="at" />
   <user="MullerS" />
        .
        .
        .
   <user="NowakA" />
   <directory="direct" />
 </department>

My question is: If I just would like to get the number of the users of a department based on id (here: 983343) dumped in a variable - what would be the bash-command (Python cannot be used)? Note too that the id might exist at another point as well inside the XML file with a different meaning that time.

Upvotes: 0

Views: 70

Answers (1)

SzG
SzG

Reputation: 12629

var=`sed -n '/department=..* id="983343"/,/<\/department>/p' file | grep -c '<user="'`

First I tell sed to print lines between the start of your specific department and its closing tag.

The result is piped into grep which looks for lines with a user tag, but counts them instead of printing them (-c option).

The entire command is placed inside backticks, so you can capture the count into a variable using command substitution.

Upvotes: 2

Related Questions