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

How do I remove trailing whitespace from all lines?

Answer

:%s/\s\+$//

Explanation

The :%s/\s\+$// command removes trailing whitespace (spaces and tabs) from every line in the file.

How it works

  • % applies to all lines
  • \s\+ matches one or more whitespace characters
  • $ anchors to end of line
  • The empty replacement // deletes the matched whitespace

Example

hello   
world  
foo

After :%s/\s\+$//:

hello
world
foo

Tips

  • Add e flag to suppress error when no match: :%s/\s\+$//e
  • Create an autocommand to do this on save
  • :set list with listchars shows trailing whitespace visually
  • Many linters flag trailing whitespace as a style issue

Next

How do you yank a single word into a named register?