One can use a command such as the following to substitute the word "before" to the word "after" where "before" occurs between the pair of words "begin" and "end":
sed '/begin/,/end/ {s/before/after/g}'
I am looking for a way to substitute "before" by "after" only if they do not occur inside a pair of "begin" and "end".