====== BASH - Files - Find & Replace a String within a File ======
See: [[BASH:Strings:Find & Replace|Find & Replace]].
----
===== Changing contents within a file =====
contents=$(< infile.txt)
$ echo "${contents/$old/$new}"
**NOTE:** This reads the file into a Bash variable and uses parameter expansion.
* **infile.txt**: The input file here is named **infile.txt**.
* **$old**: The string to replace.
* **$new**: The replacement string.
----
To change the file in-place:
echo "${contents/$old/$new}" > infile.tmp && mv infile.tmp infile.txt
----
===== Put the output of file1 into the pattern space of file2 =====
aaaaaaaaaaaaaaaaaa //these line go in file2
aaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaa
Pattern_start
__________ //these are the line to be replaced
__________
Pattern_end
sed -n '/Pattern_start/,/Pattern_end/{/^Pattern/! d;}" file2 | sed "/Pattern_start/r file1"
**NOTE:**
* **/^Pattern/**: Used this to avoid deleting the **Pattern_start** and **Pattern_end** lines.
----
If the lines between Pattern_start and Pattern_end contain only hyphens then you can use this:
sed -n '/Pattern_start/,/Pattern_end/{/^---*/d;}" file2 | sed "/Pattern_start/r file1"