Ubuntu – How can sed match pattern delete line plus one and insert diferent file

sed

I believe i'm pretty close but there is 1 command missing..

i have file1.txt

rrrrrrrrrrrrrrrrr
dddddddddddddddddd
id="8" efwef
aaaaaaaaaaaaaaaaaaa
cccccccccccccccccccc
xxxxxxxxxxxxxxxxxxxxx

file2.txt

123

123

what i need is :

rrrrrrrrrrrrrrrrr
dddddddddddddddddd
123

123
cccccccccccccccccccc
xxxxxxxxxxxxxxxxxxxxx

explained: find pattern (id="8")
delete pattern line +1
insert into file1.txt content of file2.txt

i got this sed command

sed -e '/id="8"/,+1{' -e 'r /tmp/file2.txt' -e 'd' -e '}' -i /tmp/file1.txt

it does all i need … except it inserts file2.txt twice…

probably because the ,+1 but i tryed several combos but can't get to it

Best Answer

Instead of trying to specify the next line via an address range, try using N to pull it into the pattern space before the d:

$ sed -e '/id="8"/{r file2.txt' -e 'N;d;}' file1.txt
rrrrrrrrrrrrrrrrr
dddddddddddddddddd
123

123
cccccccccccccccccccc
xxxxxxxxxxxxxxxxxxxxx