vimtricks.wiki Concise Vim tricks, one at a time.

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/, /g to 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/, /g joins 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; gJ joins without adding any space — but neither supports custom separators
  • To join every group of N lines, use a macro or :g command: :g/./if line('.')%3|norm J joins every 3 lines
  • You can also use :'<,'>!tr '\n' ',' to pipe through tr for simple character replacements
  • Combine with :g to selectively join: :g/^item/.,+1s/\n/, / joins each item line with the line below it

Next

How do I edit multiple lines at once using multiple cursors in Vim?