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

How do I find trailing whitespace while skipping completely blank lines in Vim?

Answer

/\S\zs\s\+$

Explanation

A plain trailing-whitespace search like /\s\+$ also matches fully blank lines, which is noisy when you only want accidental spaces after real content. This pattern narrows matches to whitespace that follows at least one non-whitespace character on the same line. It is a small regex refinement, but in cleanup passes it removes a lot of false positives.

How it works

  • \S requires at least one non-whitespace character on the line
  • \zs sets the real match start at that position boundary
  • \s\+$ then matches only the run of trailing whitespace at line end

Because \zs resets the match start, only the trailing spaces are highlighted, not the preceding content.

Example

Given this text:

let a = 1··

let b = 2	


(Here · and represent actual trailing whitespace.)

Using:

/\S\zs\s\+$

Matches line 1 and line 3 trailing whitespace, but ignores blank separator lines that contain no content.

Tips

  • Pair with :set hlsearch during cleanup sessions
  • Use n/N to step through only meaningful trailing-space issues
  • For one-shot cleanup, adapt the same logic in substitution form: :%s/\S\zs\s\+$//

Next

How do I append the same suffix to every selected line in Visual mode?