Awk or Sed: grep data between XML multilines

I’m trying to grep and show data from XML file through Awk or Sed, but reached an impasse…

In details I’m looking how to do the following: (1) get value from ‘mt’ tag, (2) analyze all ‘moid’ tags which contain ‘Source = _SYSTEM’ only, (3) get value of ‘Host=’ and in next line get value of ‘r’ tag, (4) then print value from ‘mt’ tag, (5) then print value of ‘Host=’ and print value of ‘r’ tag, (6) sum values from all ‘Host=’ and print it;

The problem here is that I have many tags and many lines in the XML.

Here is my XML to parse,

<?xml version="1.0"?>
<neid>
<neun></neun>
<nedn>element=home</nedn>
</neid>
<mi>
    <mts>20150517032500.0+0200</mts>
    <gp>300</gp>
    <mt>Name1</mt>
    <mv>
        <moid>Host=super1.stackoverflow.com, Source = Source1</moid>
        <r>1</r>
    </mv>
    <mv>
        <moid>Host=super2.stackoverflow.com, Source = Source2</moid>
        <r>1</r>
    </mv>
    <mv>
        <moid>Host=super2.stackoverflow.com, Source = _SYSTEM</moid>
        <r>2</r>
    </mv>
    <mv>
        <moid>Host=super2.stackoverflow.com, Source = Source3</moid>
        <r>1</r>
    </mv>
    <mv>
        <moid>Host=super1.stackoverflow.com, Source = _SYSTEM</moid>
        <r>2</r>
    </mv>
    <mv>
        <moid>Host=super1.stackoverflow.com, Source = Source4</moid>
        <r>1</r>
    </mv>
</mi>
<mi>
    <mts>20150517032500.0+0200</mts>
    <gp>300</gp>
    <mt>Name2</mt>
    <mv>
        <moid>Host=super1.stackoverflow.com, Source = Source1</moid>
        <r>11</r>
    </mv>
    <mv>
        <moid>Host=super2.stackoverflow.com, Source = Source2</moid>
        <r>11</r>
    </mv>
    <mv>
        <moid>Host=super2.stackoverflow.com, Source = _SYSTEM</moid>
        <r>22</r>
    </mv>
    <mv>
        <moid>Host=super2.stackoverflow.com, Source = Source3</moid>
        <r>11</r>
    </mv>
    <mv>
        <moid>Host=super1.stackoverflow.com, Source = _SYSTEM</moid>
        <r>22</r>
    </mv>
    <mv>
        <moid>Host=super1.stackoverflow.com, Source = Source4</moid>
        <r>11</r>
    </mv>
</mi>

Expected result,

Name1:
   super1.stackoverflow.com: 2
   super2.stackoverflow.com: 2
   TOTAL: 4

Name2:
   super1.stackoverflow.com: 22
   super2.stackoverflow.com: 22
   TOTAL: 44

Thank you a lot in advance!


Source: xml

Leave a Reply