1

I have two files file1 & file2.

Contents of file1:

Text1
Text2
Text3

Contents of file2:

Sample1 
Sample2
Sample3

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?

Thushi
  • 9,498
  • You want to insert the whole file? Is it necessary to use sed or would an awk solution be OK, too? – Hauke Laging Feb 05 '15 at 14:07
  • Yeah the whole file.I can use awk or sed – Thushi Feb 05 '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 05 '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 05 '15 at 14:26
  • jordanm: Aaah sorry the file1 contains the other text also...Updated the question. – Thushi Feb 06 '15 at 04:46
  • @don_crissti - funny, I only noticed your comment at all after spending 5 minutes trying to find a link to that question because I wanted to vote to close this one. My answer does not stand alone there either - nor even tall - awk, ed, and sed are all well represented. All three answers not only provide workable solutions, but also describe how and why the solutions are workable. – mikeserv Feb 06 '15 at 05:55
  • @don_crissti @mikeserv: Ok...Finally I eneded up by adding the below lines sed -i '/Text1/r file1' file2 sed -i '/Text1/d' file2 – Thushi Feb 06 '15 at 06:13

2 Answers2

0

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

or

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.

Costas
  • 14,916
-1

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
devnull
  • 5,431
  • No this is not the case.The file1 contains the other information also not only text1.Updated the question. – Thushi Feb 06 '15 at 04:48