Issue splitting file based on XML tags

more a-d.txt1

<a-dets>
<a-serv>
<aserv>mymac14,mymac15:MYAPP:mydom:/web/domain/mydom/config
<NMGR>:MYAPP:/web/bea_apps/perf/NMGR/NMGR1034
<a-rep-string>
11.12.10.01=192.10.00.26
10.20.18.10=192.10.00.27
</a-rep-string>
</a-serv>
<w-serv>
<wserv>mywmac3,mywmac4:MYAPP:dev.MYAPP01.mycomp.com:/web/apache/2.4.10/https-MYAPP01/conf
<web-replace-string>
</web-replace-string>
</w-serv>
</a-dets>

I need to save the contents of first occurrence of <a-dets></a-dets> in app1.tmp and the next occurrence if found in the app2.tmp and so on.

It used to work on my previous Operating System using the below command.

awk '/<a-dets>/{A=1;++i} A{print >> ("app"i".tmp")} /<\/a-dets>/{A=0} ' a-d.txt1

But it does not work on my current OS i.e Linux mymac 2.6.18-416.el5 #1 SMP Wed Oct 26 12:04:18 EDT 2016 x86_64 x86_64 x86_64 GNU/Linux

Question:

  1. Can you please help explain what went wrong and why is the awk not extracting the data between the tags ? Is that acceptable or fault in the command ?

  2. Can i use sed instead of awk to achieve the same as awk has too many flavors to deal with and i want this to run on most OS.

Hello mohtashims,

There could be 2 possibilities.
I- If you have used above shown sample Input_file only, then obviously it will show 1 app file only as I could see only occurrence of <a-dets> , so you could try with Input_file which is having 2 or more occurrences of it.
II- You could a little change to your code(though not tested it) as follows.

awk '/<a-dets>/{A=1;++i} A{print >> ("app"i".tmp")} /<\/a-dets>/{A=""}'  Input_file

Highlighted bold part only I have changed in above code, both are working fine for me, kindly do let me know on same, how it goes.

Thanks,
R. Singh

Again and again and again: WHAT "does not work", and how?

What you posted works pretty well on my linux system.