Search code examples
regexjoinvimlinesseparator

How to join lines adding a separator?


The command J joins lines.
The command gJ joins lines removing spaces

Is there also a command to Join lines adding a separator between the lines?

Example:

Input:

text
other text
more text
text

What I want to do:
- select these 4 lines
- if there are spaces at start and/or EOL remove them
- join lines adding a separator '//' between them

Output:

text//other text//more text//text

Solution

  • You can use :substitute for that, matching on \n:

    :%s#\s*\n\s*#//#g
    

    However, this appends the separator at the end, too (because the last line in the range also has a newline). You could remove that manually, or specify the c flag and quit the substitution before the last one, or reduce the range by one and :join the last one instead:

    :1,$-1s#\s*\n\s*#//#g|join