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

How do I remove trailing spaces only within the currently selected visual block?

Answer

:'<,'>s/\%V\s\+$//

Explanation

Sometimes you need to clean alignment artifacts in a rectangular region without touching the rest of each line. A normal trailing-whitespace substitution is too broad for that job. The \%V atom constrains the match to the last visual area, which makes this command ideal for surgical cleanup in tables, aligned assignments, or fixed-width text blocks.

How it works

  • Enter visual block or visual line mode and select the target region first
  • :'<,'> applies the Ex command to the selected line range
  • s/.../.../ performs substitution on each addressed line
  • \%V limits the match to columns inside the prior visual selection
  • \s\+$ matches whitespace at the end of that in-selection segment

Example

Imagine only the right-hand column of this block should be cleaned:

name    = alice    
email   = [email protected]  
status  = active    

After selecting that right-side area and running the command:

name    = alice
email   = [email protected]
status  = active

Whitespace outside the selected region is left untouched.

Tips

  • Use this with visual block mode (<C-v>) for precise column-scoped cleanup.
  • Add the e flag (...//e) if you want to suppress "pattern not found" messages on non-matching lines.

Next

How do I run a quickfix refactor once per file instead of once per match?