How do I join multiple lines together with a custom separator like a comma?
Answer
:'<,'>s/\n/, /g
Explanation
Vim's J command joins lines with a single space, but sometimes you need a custom separator like a comma, pipe, or semicolon. By substituting newline characters (\n) within a visual selection, you can join lines with any separator you choose.
How it works
- Select the lines you want to join in visual line mode (
V) - Type
:which prefills:'<,'> - Append
s/\n/, /gto replace every newline within the selection with,(comma and space) - The selected lines collapse into a single line with your chosen separator
Note: the last line in the selection does not end with \n in the match context, so you won't get a trailing separator.
Example
Given the text:
apple
banana
cherry
date
Select all four lines with VGG, then run :'<,'>s/\n/, /g:
apple, banana, cherry, date
Use a pipe instead: :'<,'>s/\n/ | /g
apple | banana | cherry | date
Tips
- For a quick one-liner without visual selection, use a range:
:1,4s/\n/, /gjoins lines 1 through 4 - The external command
:%!paste -sd,achieves the same result using Unix tools - If you want to join with no separator (concatenating lines directly), use
:'<,'>s/\n//g J(uppercase) joins with a space and removes leading whitespace;gJjoins without adding any space — but neither supports custom separators- To join every group of N lines, use a macro or
:gcommand::g/./if line('.')%3|norm Jjoins every 3 lines - You can also use
:'<,'>!tr '\n' ','to pipe throughtrfor simple character replacements - Combine with
:gto selectively join::g/^item/.,+1s/\n/, /joins eachitemline with the line below it