How to add Xml tags to an existing xml using shell or awk?

Hi ,

I have a below xml:

<ns:Body>
<ns:result>
<Date Month="June"  Day="Monday:/>
</ns:result>
</ns:Body>

i have a lookup abc.txtt text file with below details

Month  June July August
Day    Monday Tuesday Wednesday

I need a output xml with below tags

<ns:Body>
<ns:result>
<Date Month="June"  Day="Monday:/>
<Date Month="July"  Day="Tuesday:/>
<Date Month="August"  Day="Wednesday:/>
</ns:result>
</ns:Body>

How can i achieve it using awk or shell scripting

awk -v max=0 'BEGIN{ print "<ns:Body>\n<ns:result>"; }
/^Month/ {for (i=1;i<=NF;i++) {M=$i;}if(NF>max) {max=NF}}
/^Day/{for (i=1;i<=NF;i++) {D=$i;} if(NF>max) {max=NF} }
END { for (i=2;i<=max;i++) {print "<Date Month=\""M"\"  Day=\""D"\"/>";}
print "</ns:result>\n</ns:Body>"; }' lookup_file

Hope this helps. :slight_smile:

The code worked perfectly. However now i have a new requirement . the value of a particular tag is dynamic . How do i incorporate pattern matchin for a variable in the same code.

my new xml is

<ns:Body>
<ns:result>
<class classname="date">
<Date Month="June"  Day="Monday:/>
</class>
<class classname="time">
<time minutes="30" seconds="12"/>
</class>
</ns:result>
</ns:Body>

Here the value June is obtained in the following way

abc="month"
var=x_$abc

the lookup file has entry

x_month June July August
y_month June august
Day    Monday Tuesday Wednesday

The value if var needs to be used to match against the config file. How do i use the shell variable in awk in this case.