This question already has an answer here:

I have two files file1 & file2.

Contents of file1:


Contents of file2:


I would like to replace the word Text1 from file1 with the contents of file2. I already tried the below commands:

sed -i 's/Text1/r file2/g' file1
sed -e 's/Text1/`cat file1`/' < file2

Neither of which worked, what am I missing?

marked as duplicate by mikeserv, Celada, jasonwryan, Anthon, don_crissti Feb 6 '15 at 8:01

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • You want to insert the whole file? Is it necessary to use sed or would an awk solution be OK, too? – Hauke Laging Feb 5 '15 at 14:07
  • Yeah the whole file.I can use awk or sed – Thushi Feb 5 '15 at 14:07
  • 1
    Based on your description of what you want to do, it sounds like cp file2 file1 should work. If this is not the case, please clarify your question. – jordanm Feb 5 '15 at 14:21
  • 1
    If you want to replace just one word in your file with the content of another file, there's a similar question here: Insert text from file inline after matching pattern in another file. `You could modify mike's second solution and have it replace the pattern with the content of another file. – don_crissti Feb 5 '15 at 14:26
  • jordanm: Aaah sorry the file1 contains the other text also...Updated the question. – Thushi Feb 6 '15 at 4:46

If all you want to do is replace file1 with file2's contents, then any of the following will work:

cat file2 > file1

cp file2 file1
  • No this is not the case.The file1 contains the other information also not only text1.Updated the question. – Thushi Feb 6 '15 at 4:48

If you want to replace just a word (not a full sting) you have to use some trick:

sed "s/100/$(cat -E file2 |tr -d '\n')/;s/\\$/\n/g" file1


sed -e s/100/$(tr \\n $ < file2)/ -e s/\\$/\\n/g file1

The main idea that sed is a string editor so it can't accept multiline string (that is mean with newline symbols) in most case. The trick is to strip the newline symbols from file to exchange, make substitution and than put them back.

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