Skip to content
Advertisement

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.

Advertisement

Answer

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, using -i to modify the file in place:

sed -i "s@name@$(cat file1)@g" file2

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 opens both file1 and file2 itself (rather then relying on the shell or cat to open files), then it’s probably impossible.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement