What you've done is to remove SUBSTITUTETHIS
wherever it appears in the file (but not the rest of the line where it appears) and insert the content of temp.TXT
below that line. If SUBSTITUTETHIS
appears multiple times on a line, only the first occurrence is removed, and only one copy of temp.TXT
is added.
If you want to replace the whole line when SUBSTITUTETHIS
appears, use the d
command. Since you need to run both r
and d
when there's a match, put them in a braced group.
sed -e '/SUBSTITUTETHIS/ {' -e 'r temp.TXT' -e 'd' -e '}' -i devel.txt
Some sed implementations let you use semicolons to separate commands and omit separators altogether around braces, but you still need a newline to terminate the argument to the r
command:
sed -e '/SUBSTITUTETHIS/ {r temp.TXT
d}' -i devel.txt
If you want to replace SUBSTITUTETHIS
by the content of the file, but retain what comes before and after it on the line, it's more complicated. The simplest method is to include the content of the file in the sed command; note that you'll have to properly quote its contents.
sed -e "s/SUBSTITUTETHIS/$(<temp.TXT sed -e 's/[\&/]/\\&/g' -e 's/$/\\n/' | tr -d '\n')/g" -i devel.txt
Or use Perl. This is short but runs cat
once for each substitution:
perl -pe 's/SUBSTITUTETHIS/`cat temp.TXT`/ge' -i devel.txt
To read the file once when the script starts, and avoid depending on a shell command:
perl -MFile::Slurp -pe 'BEGIN {$r = read_file("temp.TXT"); chomp($r)}
s/SUBSTITUTETHIS/$r/ge' -i devel.txt
(presented on two lines for readability but you can omit the line break). If the file name is variable, to avoid quoting issues, pass it to the script via an environment variable:
replacement_file=temp.TXT perl -MFile::Slurp -pe 'BEGIN {$r = read_file($replacement_file); chomp($r)}
s/SUBSTITUTETHIS/$r/ge' -i devel.txt