Here is one way of doing it that uses built-in functionality only:
With point in the line that contains first occurrence of begin
, press C-SPC.
Move to next occurrence of end
:
C-s end
RET
Replace foo
with bar
:
M-% foo
RET bar
RET !
This makes use of the fact that query-replace
will work on the active region instead of the whole buffer if there is one.
Of course, you can also define a custom command:
(defun replace-from-to (beg end str repl)
(interactive "sBegin: \nsEnd: \nsString: \nsReplacement: ")
(save-excursion
(goto-char (point-min))
(let ((start-pos (search-forward beg))
(end-pos (search-forward end)))
(replace-string str repl nil start-pos end-pos))))
This command will always search from the beginning of the buffer, so point can be after begin
/foo
/end
when you invoke it.
Set up a key binding for it via:
(global-set-key (kbd "C-c r") 'replace-from-to)