MuhammadNe MuhammadNe - 10 months ago 58
Linux Question

How to replace a word in a file with a word in another file in Linux

I want to change a word in a file, with another word that I get from another file.

Let's say I have 2 files :

File #1 contains : jack

File #2 contains : Hello name

How can I replace the word "name" with "jack"?

PS. File #1 contains only this word, no need for any regex.

pts pts
Answer Source

This shell command will do the replacement using Perl:

NAME="$(cat file1)" perl -pi -e 's@name@$ENV{NAME}@g' file2

An alternative with Perl:

perl -pi -e "s@name@$(cat file1)@g" file2

An alternative with sed, writing the output to a separate file.

sed "s@name@$(cat file1)@g" <file2 >file2.out

All of the solutions above assume that file1 doesn't contain newlines (except possibly for the trailing newline), backslashes and at signs (@).

If you want a pure sed solution which modifies file2 in place, and it opens both file1 and file2 itself (rather then relying on the shell or cat to open files), then it's impossible.