Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

vim

Sometimes I accidentally leave blank lines at the end of the file I am editing.
How can I trim them on saving in Vim?

Update

Thanks guys, all solutions seem to work.
Unfortunately, they all reset current cursor position, so I wrote the following function.

function TrimEndLines()     let save_cursor = getpos(".")     silent! %s#\($\n\s*\)\+\%$##     call setpos('.', save_cursor) endfunction  autocmd BufWritePre *.py call TrimEndLines() 
like image 641
gennad Avatar asked Sep 21 '11 07:09

gennad


People also ask

How do I delete blank lines in Vim?

:g/^\s*$/d - Remove all blank lines. Unlike the previous command, this also removes the blank lines that have zero or more whitespace characters ( \s* ).

How do you remove blank rows in Linux?

Delete blank lines using the grep command When used with the -v option, the grep command helps to remove blank lines. Below is a sample text file, sample. txt, with alternative non-empty and empty lines. To remove or delete all the empty lines in the sample text file, use the grep command as shown.


1 Answers

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.

like image 126
Prince Goulash Avatar answered Sep 27 '22 22:09

Prince Goulash