For in-place editing with GNU sed, there's the -i option. The Read line command, (which reads one line from a named file, then each line after that when run again), is useful here. Two line version:
sed -i `1'1,5{R file2
d}`' file1
Notes:
Read line's output is not changed by thedelete that follows.Rinserts each line from file2 afterddeletes a line from file1. Thedcannot go first, (if it doesdid, theRoutputs nothing);command would not be run,Rdneeds an existing line to work with.is likenextinawk)The
Read line (like all commands taking a file name) requires the filename be delimited by a linefeed or an unquote. The usual;command separator is ignored,RinterpretsR file2;as a filename ending with a literal ";". The same with spaces,RinterpretsR file2 ;as a filename ending with a literal ";"Ris not affected by-i, so file2 won't be changed.
Therefore toTo fit that on one line requires breaking up the curly braces with an unquote and, one can pass two -e switchesxpressions which sed joins with linefeeds to form the sed script:
sed -i -e '1,5{R file2' -e 'd}' file1
Otherwise, you don't need sed:
{ head -n 5 file2; tail -n +6 file1; } > file3
In the general case, to replace $x1 to $y1 lines of file1 with $x2 to $y2 lines of file2:
sed "$x2,\$!d;$y2 q" file2 | sed -i -e "$x1 r /dev/stdin" -e "$x1,$y1 d" file1
Or:
{
head -n "$((x1 - 1))"
tail -n "+$x2" < file2 | head -n "$((y2 - x2 + 1))"
tail -n "+$((y1 - x1 + 2))"
} < file1 > file3