Replacing a single line with multiple lines in a file

Hi

Am confused with the usage of "sed" command

I want to replace a single line with multiple lines of a file..

eg.,
A file has

Hi, How are you?

I need to replace as

 Am fine
What are You doing?

I used the script as

string1="Hi, How are you?"
echo "$string1 is the value"
replace1="Am fine
What are you doing?"
echo "$replace1 is the value"
cat file | sed -e "s/$string1/$replace1/g" > file_new

Here the values of $string1 and $replace1 prints the value whereas in the sed command i get the error as
sed: 0602-404 Function cannot be parsed.

Please help whether my usage of sed command is correct.
If not, please suggest me how to replace the contents of file by using any other command, if the usage of sed command is not comfortable..
:rolleyes::rolleyes:

string1="Hi, How are you?"
echo "$string1 is the value"
replace1="Am fine\\
What are you doing?"
echo "$replace1 is the value"
cat file | sed -e "s/$string1/$replace1/g" > file_new

This can be also done with awk command instead of sed..
Place the lines to be replaced in a file with name file.txt

cat file.txt

Am fine
What are you doing?

Instead of sed use the following:

awk '/Hi, How are you?/{system("cat file.txt");next}1' file > file_new

Now, the file_new contains the new replaced lines mentioned in file.txt..

string1="Hi, How are you?" 
echo "$string1 is the value" 
replace1="Am fine\nWhat are you doing?" 
echo "$replace1 is the value" 
sed -e "s/$string1/$replace1/g" file > file_new

this can be done in sed/awk/perl/python all of these, your question was for sed :slight_smile:

1 Like

How about the following shell script, using sed:

string1="Hi, How are you?"
echo "Am fine" > temp.x
echo "What are you doing?" >> temp.x
sed -e "/$string1/r replace.txt" -e "//d" file > file_new
rm temp.x