1

I have a simple xml file somewhat like:

<student>
</student>

I am using this sed command:

    sed -i "s/<\/student>/  <name>${1}<\/name>\
      <age>${2}<\/age>\
<\/student>/g" pom.xml

to replace my xml with some xml data using the command:

./main.sh JohnDoe 12

and based on the command line values it should print as

<student>
  <name>JohnDoe</name>
  <age>12</age>
</student>

But is ending up printing as

   <student>
     <name>JohnDoe</name>  <age>12</age>  </student>

So how can I format my xml data neatly using sed!!

Thanks for the help in advance!!

KNDheeraj
  • 834
  • 8
  • 23
  • While this is a totally legitimate question, it feels like a different incarnation of https://stackoverflow.com/q/1732348/2988730 – Mad Physicist May 21 '19 at 11:42
  • OP, I suggest you recast your question in terms of abstract text instead of XML if you want to get good answers faster. There is a lot of (mostly justified) emotion that comes with XML that brings on more bikeshedding than real information. – Mad Physicist May 21 '19 at 11:47

3 Answers3

1
sed -i "s/<\/student>/  <name>${1}<\/name>\n  <age>${2}<\/age>\n<\/student>/g" pom.xml

Keep in mind that parsing xml by sed or awk is not recommended, search here for parse xml bash

lojza
  • 1,823
  • 2
  • 13
  • 23
0

After working on this problem for few days!! I was able to come up with a solution

#!/bin/bash

newLine=\\n

sed -i "s/<\/student>/  <name>${1}<\/name>${newLine}\
  <age>${2}<\/age>${newLine}\
<\/student>/g" pom.xml

creating a new line \n Variable and adding it at the end of each Line worked out...

KNDheeraj
  • 834
  • 8
  • 23
-2

XML is a markup language with its semantics and it should not be parsed/manipulated with such tools as sed. Use appropriate XML/HTML parsers/processors.

With xmlstarlet tool:

sample test.xml content:

<student>
</student>

test.sh script content:

#!/bin/bash

xmlstarlet ed -s "student" -t elem -n name -v "$1" -s "student" \
           -t elem -n age -v "$2" test.xml | xmlstarlet fo -o -

Usage:

$ . test.sh John 35

Output:

<student>
  <name>John</name>
  <age>35</age>
</student>

Documentation link: http://xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html#idm47077139594320

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • While your point is valid, this does not answer the question. How do you get the sed command to work? Forget that it's XML for a second. What if OP had `A\nA` but wanted `A\n B\n B\nA`? – Mad Physicist May 21 '19 at 11:44
  • @MadPhysicist, forgetting about XML when working explicitly with XML? that sounds more than strange (and does not correlate with correct and robust approaches) – RomanPerekhrest May 21 '19 at 11:48
  • Forget about XML when the title, tags and body of the question make it clear that it is irrelevant to the situation, yes. For some reason, mentioning XML seems to make things harder. – Mad Physicist May 21 '19 at 11:53
  • this answer is a bit too opinionated – CervEd Dec 16 '21 at 20:38