Search code examples
regexvimnewlinecarriage-returnlinefeed

Why \n line feed works in find and \r carriage return works in replace as new line?


I got a file with text in this format. (with unwanted line spaces)

1

2

3

Now I wanted to use vim to remove those unwanted lines with this command :%s/\n\n/\n/g. replacing two new lines with one. But got this result:

1^@2^@3

then I found out about carriage return and used this post to change the command to :%s/\r\r/\r/g and got this error saying E486: Pattern not found: \r\r

then I used this working command :%s/\n\n/\r/g and got the desired result.

1
2
3

How is this working?


Solution

  • The \r in the pattern matches a carriage return (CR) char, not any line break char. The \r construct should used in the replacement pattern to replace with a newline.

    So, you can use either

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

    or, to replace chunks of any two or more newline chars with a single newline:

    :%s/\n\{2,}/\r/
    

    To account for CRLF endings, you can use

    :%s/\v(\r?\n){2,}/\r/
    

    that matches two or more ({2,}) sequences of an optional CR char (\r?) and then a newline, line feed (LF) char.