How do I join all lines in a file into one, or use a custom separator when joining?
Answer
:%s/\n/ /g
Explanation
Using \n in the pattern of :substitute matches the newline character at the end of each line, letting you join lines with any separator you choose — something the J command and :join cannot do.
How it works
%— apply to every line in the files/\n/ /g— replace each line-ending newline with a space- Change the replacement to suit your needs: use
,to join with commas, or leave it empty (s/\n//g) to concatenate with no gap
Because Vim's :substitute can match across the newline at the end of each line, every line is collapsed into the first in a single command pass.
Example
Given a buffer with three lines:
foo
bar
baz
Running :%s/\n/ /g produces:
foo bar baz
To join with a comma separator instead:
:%s/\n/,/g
Result:
foo,bar,baz
Tips
- Use a line range to join only part of the file:
:1,5s/\n/ /g Jand:[range]joinalways join with a single space; this substitution is the only built-in way to specify a custom separator- To keep blank lines as paragraph separators while joining within paragraphs, use
:g/./,/^$/joininstead