1

I have a file called abc.xml

abc.xml

<Engine name="private" defaultHost="localhost">
    <Model name="qwerty"/>
    <Host name="localhost" />
    </Engine>

I would like to add subtag in Host tag so that my modified abc.xml will look like as below.

<Engine name="private" defaultHost="localhost">
<Model name="qwerty"/>
    <Host name="localhost" company="jaguar" >
       <Partner name="xxx" />
       <Partner name="yyy" />
    </Host>
    </Engine>

How to achieve above changes using SED or awk command?

Maverick
  • 11
  • 2

2 Answers2

1

With xmlstarlet, you could do it like this:

 xmlstarlet ed -i //Host -t attr -n company -v jaguar \
    -s //Host -t elem -n Partner \
    -i //Host/Partner -t attr -n name -v xxx \
    -s //Host -t elem -n Partner \
    -i //Host/Partner[2] -t attr -n name -v yyy abc.xml

Now, this looks a bit more involved, but it is aware of the structure of your file.

Michael Vehrs
  • 3,293
  • 11
  • 10
0

cat ins.txt

<Host name="localhost" company="jaguar" >
       <Partner name="xxx" />
       <Partner name="yyy" />

cat abc.xml

<Engine name="private" defaultHost="localhost">
    <Model name="qwerty"/>
    <Host name="localhost" />
    </Engine>

cat script.awk

BEGIN{RS=""}
ARGV[1]==FILENAME{ins=$0;RS="\n";next}
/<Host/ {print ins;next} 1

awk -f script.awk ins.txt abc.xml

<Engine name="private" defaultHost="localhost">
    <Model name="qwerty"/>
    <Host name="localhost" company="jaguar" >
       <Partner name="xxx" />
       <Partner name="yyy" />
    </Engine>
Chet
  • 1,205
  • 1
  • 12
  • 20