4

I need to insert lines into an xml file :

Insert

  <one>
  </one>

into

<tags>
</tags>

To obtain

<tags>
  <one>
  </one>
</tags>

I tried this:

sed "s#\\(< /tags>\\)#${multiline_string}\1#"

but it loses the indentation.

  • Why is losing the indentation a problem? It should not be for XML files. – Mat Feb 24 '12 at 15:58
  • @Mat If it is data instead of just tags, it matters. – Chris Down Feb 24 '12 at 16:05
  • @Mat It is a problem because this xml (a maven pom) is read and modified by humans. – Philippe Blayo Feb 24 '12 at 16:31
  • @Philippe Blayo: Your sed script wasn't far off the mark. This works: sed "s|\(</tags>\)|${multiline_string//$'\n'/\n}\1|" ... but larsks' append method may be more obvious. – Peter.O Feb 24 '12 at 17:04
  • @Peter.O Why did you submit that as a comment? – Chris Down Feb 24 '12 at 22:10
3

As Mat said, indentation (and whitespace in general) is not important in XML files. This:

<one><tags></tags></one>

Is exactly equivalent to:

<one>
 <tags>
 </tags>
</one>

But this will work while preserving indentation:

$ cat myfile.xml
<tags>
</tags>
$ sed '/<one>/ a\
  <tags>\
  </tags>
' myfile.xml > newfile.xml
$ cat newfile.xml
<one>
  <tags>
  </tags>
</one>

...but if you're working with XML, you might want to think about using a higher-level language that can actually parse XML and manipulate the tree programatically.

0

The following is a mod to the code you show in the question.

Note that $'\n' is a ksh (also supported by bash and zsh) way to make a newline char, so adjust as needed if you are using another shell.

sed "s|\(</tags>\)|${multiline_string//$'\n'/\n}\1|g"

The trailing g is to cater for situations where you may have </tags> occurring more than once on a line.. It seems that it isn't needed for your xml, but it works either way.

  • Note that \n to mean a newline character in the RHS of the s command is not portable/standard. The standard way is a backslash followed by a newline character. – Stéphane Chazelas Jan 4 '13 at 22:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.