11

Lets say i have two files foo and bar. I want a replace the string "this is test" in foo with the contents of the file bar. How can i do this using a one liner sed?

I have used:

sed -i.bak 's/this is test/$(cat bar)\n/g' foo 

but the the string is being replaced by literal $(cat bar) rather than the contents of bar. I have tried using quotations but the result remains the same.

Radu's answer is correct as far as the quote is concerned. Now the problem is lets say my bar file contains:

this
is
a
test
file

Now if i run the command it gives an error:

sed: -e expression #1, char 9: unterminated `s' command

18 times.

heemayl
  • 91,753

3 Answers3

10

The following command should work for what you want:

sed "s/this is test/$(cat bar)/" foo

If foo contain more then one line, then you can use:

sed "s/this is test/$(sed -e 's/[\&/]/\\&/g' -e 's/$/\\n/' bar | tr -d '\n')/" foo

or:

sed -e '/this is a test/{r bar' -e 'd}' foo

Source of the last two commands: Substitute pattern within a file with the content of other file

To make the change in foo file, use sed -i.

Radu Rădeanu
  • 169,590
7

One way:

sed -e '/this is test/r bar' -e '/this is test/d' foo

Sample result:

$ cat bar
12
23
$ cat foo
ab
this is test
cd
this is test
ef
$  sed -e '/this is test/r bar' -e '/this is test/d' foo
ab
12
23
cd
12
23
ef
Guru
  • 729
1

When you need to replace an entire line with the contents of a file, you can use r to insert a file and d to delete the current line:

sed -e "/regex/{r/path/to/file" -e "d}"
aleb
  • 136