awk command to insert a tag in XML

Hi All,

I need a help on inserting a XML tag.
Actual input

<var>
<nam>abcd</nam>
<a1>.</a1>
</var>

if tag

<a1>.</a1>

is getting missed in XML like below

<var>
<nam>abcd</nam>
</var>

i need to insert wherever it is missed after <nam> tag and before </var> tag.
Could anyone help me on this.Thank you

---------- Post updated at 08:43 AM ---------- Previous update was at 07:25 AM ----------

I tried the below code but gting syntax error at else part,
file.txt will be having the

<a1>.</a1>
 
awk -v f="file.txt" '{ if ($0!="<a1>") { while (getline < f) txt=txt $0} /<\/nam>/x sub("</var>",txt) { else print $0 } }1' input.xml

Try this:

awk '/<nam>/ {L=1} /<a1>/ {L=0} /<\/var>/ && L {print "<a1>.</a1>"} 1' input.xml
1 Like

Thanks a lot RudiC for great code. I was egarly waiting for the same post reply. Could you please explain it a bit, it will help us to improve our skills.

Thanks,
R. Singh

awk     '/<nam>/                {L=1}                   # if a line contains <nam>, keep that fact in variable L
         /<a1>/                 {L=0}                   # if then <a1> occurs, no action necessary, reset L
         /<\/var>/ && L         {print "<a1>.</a1>"}    # if end of section and L still set, print missing string.
                                                        # you might want to reset L as well to be on the safe side
         1                                              # print normal lines from file
        ' file
1 Like