Using GNU sed we can perform the task
by storing the count as dots . in the hold
space.
sed -e '
/^line 1$/,/^line 1$/{//!b
x;s/^$/./;x;t
:a;n;s/^line 3$/REPLACED/;ba
}
' file
Another possibility without using the range
operator and with extended regex mode
in GNU sed. Here the newline \n function as counter, stored in the hold space.
sed -Ee '
/^line 1$/H
x;s/^(\n{1,2}).*/\1/;x
/^line 3$/G
/\n.{2}/c REPLACED
s/\n//g
' file
Perl can do the same in a similar fashion
perl -lpe '
s/^line 3$/$a?"REPLACED":$&/e
unless
m?^line 1$? ... /^line 1$(?{$a++})/;
' file
Using awk, we can nicely combine regexes with variables and incrementing by one
awk '
1 < ( k += /^line 1$/ ) &&
sub(/^line 3$/,"REPLACED") ||
1' file