Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
    
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
show 1 more comment

2 Answers

up vote 3 down vote accepted

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.

share|improve this answer
add comment

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.

share|improve this answer
    
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. –  Stephane Chazelas Jan 4 '13 at 22:39
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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