How to join lines adding a separator?

爷,独闯天下 提交于 2019-12-21 17:25:52

问题


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

回答1:


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



回答2:


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.




回答3:


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.




回答4:


Another substitution, for the sake of diversity:

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



回答5:


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


来源:https://stackoverflow.com/questions/25201302/how-to-join-lines-adding-a-separator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!