vimtricks.wiki Concise Vim tricks, one at a time.

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 matching BEGIN through the next line matching END
  • -1 offsets the end of that range by one line upward, so the END line itself is not modified
  • s/\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 g or c flags to substitution only when needed; keep defaults for predictable batch edits
  • Use more specific markers to avoid accidental matches in large files

Next

How do I programmatically create a blockwise register with setreg()?