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?

9
  • I don't see a question here. Recommend you read: stackoverflow.com/help/how-to-ask Commented Jun 14, 2016 at 4:37
  • How to achieve above mentioned change using sed or awk command ? Commented Jun 14, 2016 at 4:37
  • Please update the question text to reflect this. And welcome to Stack Overflow! Commented Jun 14, 2016 at 4:39
  • done and thanks for warm welcome :) Commented Jun 14, 2016 at 4:40
  • 1) searching for the pattern "<Host" and deleting the whole line and adding new line instead with my changes 2) used command "$temp::2" where temp will have my pattern match string. this will remove "/>" from the end of "<Host ... />" tag. and added manually ">" at the end. Commented Jun 14, 2016 at 4:44

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.