How to remove multiple blank lines in sequence with vim?

Asked

Viewed 416 times

1

I have the following problem, I have a file with all scrambled code, many blank lines. I tried to remove the blank lines according to the post post about line deletion, but it removed all blank lines. I wanted to leave at least one blank line between each line of code.

  • I’ve tried a way now, but there’s certainly an easier way to do it. I was able to first remove all the blank lines :g/^$/:delete then positioned at the beginning of the archive gg and recorded a macro with the content: qsA<CR>j<Esc>q after saving the macro, I saw that the file was left with, for example 520 lines, so I applied the macro 520 times via command 520@s. The problem with this approach is that I must know the number of lines after removing the blank ones, i.e., is not effective.

4 answers

4


Sorry for my poor Portuguese. I used Google Translator. Edit any bad grammar you see :)


You can use the following command:

:%s/^$\n^$

This informs to vim to remove any occurrence of two empty lines next to each other. Normally, you would like to use

:%s/^$\n^$//g

To finish the command, but we don’t need the option /g because there can only be one line match, and we don’t need the diagonal bars, since the vim doesn’t require that.

1

Replace 2 or more blank lines (\n\n\n*) for two blank lines (\r\r)

:%s/\n\n\n*/\r\r/

Note: in vim, substitutions are used \r instead of \n

1

I created two functions in my ~/. vimrc The first aims to execute commands without changing the position of the cursor and search records, because when we locate consecutive blank lines in order to delete them this record is stored, that is, the Preserve function can be used in other situations.

The second is the function that will actually delete the blank lines.

if !exists('*Preserve')
    function! Preserve(command)
        " Preparation: save last search, and cursor position.
        let save_cursor = getpos(".")
        let old_query = getreg('/')
        execute a:command
        " Clean up: restore previous search history, and cursor position
        call setpos('.', save_cursor)
        call setreg('/', old_query)
    endfunction
endif


" remove consecutive blank lines
" see Preserve function definition
fun! DelBlankLines()
    keepjumps call Preserve("g/^\\n\\{2,}/d")
endfun
command! -nargs=0 DelBlank :call DelBlankLines()

If you wish you can even map to <leader>d thus:

:nnoremap <leader>d :call DelBlankLines()

OBS: <leader> by default is backslash but on many systems is set to "Comma" ,.

0

:g/^$/:delete

or

:g/^$/d
  • g = global, whole document
  • ^ = beginning of the line
  • $ = end of the line Note: the $ standard means everything that has nothing between the beginning and end of the line
  • d | delete = delete the line that matches the pattern above

Browser other questions tagged

You are not signed in. Login or sign up in order to post.