How do I run a command between two patterns but exclude the end marker line?
Answer
:/BEGIN/,/END/-1s/\s\+$//
Explanation
When you need to clean or refactor block-like regions, Ex ranges can target lines between two search patterns without selecting text manually. The subtle part is excluding the closing marker line, which is where an offset makes this command much safer for structured files.
How it works
:/BEGIN/,/END/-1s/\s\+$//
:/BEGIN/,/END/defines a range from the next line matchingBEGINthrough the next line matchingEND-1offsets the end of that range by one line upward, so theENDline itself is not modifieds/\s\+$//removes trailing whitespace on each line in the range
This pattern is useful whenever marker lines must remain untouched, for example in generated sections, fenced snippets, or hand-maintained blocks with sentinel comments.
Example
Before:
# BEGIN
alpha
beta
# END
After:
# BEGIN
alpha
beta
# END
Tips
- Replace
s/\s\+$//with any Ex command (normal!,g,s, etc.) to reuse the same range logic - Add
gorcflags to substitution only when needed; keep defaults for predictable batch edits - Use more specific markers to avoid accidental matches in large files