3

I have a problem. I would like replace a line of a file by the content of another file.

In my first file I have this line: "#Content" and I would like to replace that with the content of the file content.xml.

Thanks.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
jeremieca
  • 1,156
  • 2
  • 13
  • 38

2 Answers2

3

This can work:

your_new_text=$(cat content.xml | sed 's/[^-A-Za-z0-9_]/\\&/g')
sed -i "s/#Content/$your_new_text/" your_file

It puts the text from content.xml in the variable $your_new_text. Then sed does the work: -i stands for replacing in the file, looks for #Content and replaces by text inside $your_new_text.

Note that it has to be wrapped with " to work.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • I have the error `sed: 1: "minimize": invalid command code m`. I run under osx – jeremieca May 01 '13 at 16:04
  • 1
    From what I see in your answer (it should be in your question, though), the problem is that your content.xml file has some protected characters. Using http://stackoverflow.com/a/5329148/1983854 info, we can `cat content.xml | sed 's/[^-A-Za-z0-9_]/\\&/g'` to escape them. – fedorqui May 01 '13 at 16:07
  • Thank you, but the "newline" is not escape. I have this error : `unescaped newline inside substitute pattern`. I test that `new=$(cat $file | sed 's/[^-A-Za-z0-9_]/\\&/g' | sed 's/\n/\\&/g')` but it fails. – jeremieca May 01 '13 at 17:28
1

This can work too, not very effective - but not sensitive to content.

cat <(sed '/#Content/,$d' < FILE ) content.xml <(sed '1,/#Content/d' < FILE) > NEWFILE

so, catenate

  • the first part of FILE (up to #Content - (not included))
  • the file `content.xml
  • the second part of file (from to #Content - (not included))
clt60
  • 62,119
  • 17
  • 107
  • 194