Reman
Reman

Reputation: 8109

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

Upvotes: 5

Views: 1008

Answers (5)

jmunsch
jmunsch

Reputation: 24089

Will list 50 items per line seperated by spaces:

seq 0 70 | xargs -L 50 | sed 's/ /,/g'

Output:

0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49
50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70

Upvotes: 1

romainl
romainl

Reputation: 196476

Another substitution, for the sake of diversity:

:%s:\n\ze.://

Upvotes: 1

XLII
XLII

Reputation: 1182

There are few ways to do it, but I would recommend going by simplest route possible - recording a macro or doing multi-step command, for example by:

Appending to all lines excluding last by

  • Using substitution (:1,$-1s#$#//#)
  • Appending (:1,$-1norm A//)

And then join using visual selection (vGgJ) or by any other method.

Unless you're doing this operation very often you most likely forget any complex commands or existence of specialized plugin in your config, thus my recommendation of using generic, often used sub steps.

Upvotes: 1

Kent
Kent

Reputation: 195029

I wrote a plugin "Join", could do what you wanted, and more.

https://github.com/sk1418/Join

Except for all features provided by the build-in :join command, Join can:

Join lines with separator (string)
Join lines with or without trimming the leading/trailing whitespaces
Join lines with negative count (backwards join)
Join lines in reverse
Join lines and keep joined lines (without removing joined lines)
Join lines with any combinations of above options

check the homepage for details and examples/screenshots.

Upvotes: 3

Ingo Karkat
Ingo Karkat

Reputation: 172510

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

Upvotes: 5

Related Questions