Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have an xml file named test.xml, without a root tag like this:

<cat></cat>
<name></name>
<id></id>
<cat></cat>
<name></name>
<id></id>

How can I wrap this file with a root tag to make the output look like this:

<root>
  <cat></cat>
  <name></name>
  <id></id>
  <cat></cat>
  <name></name>
  <id></id>
</root>
share|improve this question

In line number one insert before it (i\) the opening tag, and in last line ($) append after it (a\) the closing tag (I didn't care about the formatting with spaces):

EDIT: I forgot to say that GNU version of sed is needed.

Content of script.sed:

1 i\
<root>
$ a\
</root>

Run it like:

sed -f script.sed infile

With following output:

<root>
<cat></cat>
<name></name>
<id></id>
<cat></cat>
<name></name>
<id></id>
</root>
share|improve this answer
1  
sed -i '1s/^/<root> /' test.xml Solved the Problem – HardCode Aug 14 '12 at 7:18
    
or even just sed -e '1i<root>' -e '$a</root>' -e 's/^/ /' – rush Aug 14 '12 at 8:28

You can do this with redirection:

(echo "<root>"; cat test.xml; echo "</root>") > wrapped-test.xml

And with indention:

(echo "<root>"; sed 's/^/  /' test.xml; echo "</root>") > wrapped-test.xml
share|improve this answer

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.