How can I trim blank lines at the end of file in Vim?

This substitute command should do it:

:%s#\($\n\s*\)\+\%$##

Note that this removes all trailing lines that contain only whitespace. To remove only truly “empty” lines, remove the \s* from the above command.

EDIT

Explanation:

  • \( ….. Start a match group
  • $\n … Match a new line (end-of-line character followed by a carriage return).
  • \s* … Allow any amount of whitespace on this new line
  • \) ….. End the match group
  • \+ ….. Allow any number of occurrences of this group (one or more).
  • \%$ … Match the end of the file

Thus the regex matches any number of adjacent lines containing only whitespace, terminated only by the end of the file. The substitute command then replaces the match with a null string.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)