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 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

2 Answers 2

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.