So I'm trying to replace a line content in a file with multiple lines but I can't get it to work. Here's the details:
Text File: /home/user1/file1.txt
File content:
The quick brown fox
The quick brown fox jumps over the lazy fat dog
Little brown and the lazy fat dog
Lazy dog and the fat lion
string1="The quick brown fox jumps over the lazy fat dog"
string2="The quick little black fox jumps over the lazy fat dog
The quick big brown fox jumps over the lazy fat dog
The lazy little brown fox jumps over the lazy fat dog"
Shell script file: /home/user1/replace_me.sh
So if I run the shell script file with the below sid command, the file content would be changed to:
The quick brown fox
The quick little black fox jumps over the lazy fat dog
The quick big brown fox jumps over the lazy fat dog
The lazy little brown fox jumps over the lazy fat dog
Little brown and the lazy fat dog
Lazy dog and the fat lion
I used How to replace a variable with another variable using sed and Replace a word with multiple lines using sed? as references:
These are the commands I tried with no luck :(
sed -i "s/$string1/$string2/" /home/user1/file1.txt
sed -i "/${string1}/{s/^.*/${string2}/" /home/user1/file1.txt
Below is the shell script file content:
#!/bin/bash
string1="The quick brown fox jumps over the lazy fat dog"
string2="The quick little black fox jumps over the lazy fat dog
The quick big brown fox jumps over the lazy fat dog
The lazy little brown fox jumps over the lazy fat dog"
sed -i "s/$string1/$string2/" /home/user1/file1.txt
#sed -i "/${string1}/{s/^.*/${string2}/" /home/user1/file1.txt
/beforescommand,sed -i "s/$string1/$string2/" /home/user1/file1.txtsedis generally a poor choice of tools for this job -- one needs to do escaping or else not all characters will work correctly (/, in the case of Wiktor's example above). See BashFAQ #21, and particularly the definition ofgsub_literaltherein, for tools that do it better. (There's also aperl-based alternative described in that same page).noneas per your advice to make the block a literal data. Thanks.gsub_literalis built onawk. Being POSIX-defined, that's more likely to be present.