2

I would like to replace every section of newlines - for example, a single newline at the end of a line, or 5 newlines at the end of a line until the next line of text - with a single newline.

I tried to do this with:

:%s/$\n*/\r/, but this did not result in a bunch of lines with the exact same amount of newlines between them.

Maybe the problem is that some of the seemingly "blank" lines actually have a space on them, so the expression is treating 3 blank lines as 3 separate matches and re-inserting 3 carriage returns in total.

In general, what is the most standard regex for "any amount of blank space from the end of a line with text in it until the next line with text in it", or what would be a good way to fix this?

1 Answer 1

1

You have almost did it with :%s/$\n*/\r/.

Try simpler one:

:%s/\n\+/\r

But if you want to remove all empty lines try even simpler:

:%s/^\s*$//

Update

if your text looks like:

there are


   

   

empty lines with 


some spaces

  

   that

has to be deleted

Where there are lines with spaces and you want to get

there are
empty lines with 
some spaces
    that
has to be deleted

Then %s/\n\_s*$//g would do it.

See :h /\_s for details.

PS, if you also need to delete trailing whitespaces then it would be even simpler: %s/\_s*$//g

PPS if you want to replace it with some constant number of newlines:

%s/\n\_s*$/\r\r/g

will replace all empty lines with 2:

there are    


empty lines with 


some spaces


   that


has to be deleted


PPPS, how to add N number of \r I have answered on your other question.

4
  • I think your last expression should be ˋ%s/^\s*\n//ˋ.
    – Ralf
    Sep 10, 2021 at 17:11
  • The first one will replace any number of newlines with a single newline, but it will still treat a newline, then a space, then a newline as two separate matches instead of one. The second one removes blank newlines, but it only works for collapsing sequences of blank lines to nothing, whereas I actually want to replace regions of blank lines with some number of blank lines, i.e. consistently 4 newlines, for example. So I think I need something that says, "the end of a line followed by any number of newlines or whitespace in any order". I think this might be $[\n, \s]* ?
    – hmltn
    Sep 12, 2021 at 18:37
  • It would be way simpler you had provided an example text in your question, @JohnSmith
    – Maxim Kim
    Sep 12, 2021 at 18:49
  • @JohnSmith I have updated the answer with some text before -> text after and the command
    – Maxim Kim
    Sep 12, 2021 at 18:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.