Ravichandra
Ravichandra

Reputation: 2332

How to replace a string in a file with other file.

I am trying to replace a string in a file1 with a file2

file1.txt

 This is first line in file.

file2.txt

 Hello world

I am trying to replace "This" word with "Hello World"

file1.txt

Hello world is first line in file.

I tried with sed

sed -i 's/This/`cat file2.txt`\g' file1.txt

cat file2.txt is first line in file.

Upvotes: 2

Views: 435

Answers (1)

sjsam
sjsam

Reputation: 21955

Check this link which says :

The shell is responsible for expanding variables. If you use single quotes for strings, the contents will be treated literally

Your solution is to use double quotes like below:

var=$(< file2.txt)
sed -i "s/This/$var/" file1.txt

Upvotes: 4

Related Questions