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
eflag to suppress error when no match::%s/\s\+$//e - Create an autocommand to do this on save
:set listwithlistcharsshows trailing whitespace visually- Many linters flag trailing whitespace as a style issue