Sometimes I accidentally leave blank lines at the end of the file I am editing.
How can I trim them on saving in Vim?
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()
: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* ).
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.
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 fileThus 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With