How do I join a specific range of lines into one line using an Ex command?
Answer
:[range]join
Explanation
The :[range]join Ex command lets you join lines by specifying an explicit line range — without having to navigate there or use visual selection. This makes it ideal for use inside macros, scripts, or when you already know the line numbers.
How it works
:[range]join— join lines in the range, separated by a single space:[range]join!— join lines with no separator at all (likegJin normal mode)- Range examples:
1,5join— join lines 1–5 into one line.,+3join— join the current line with the next 3'<,'>join— join the visually selected lines (same asJin visual mode, but scriptable)
Example
Given:
apple
banana
cherry
Running :1,3join produces:
apple banana cherry
Running :1,3join! (no spaces) produces:
applebananacherry
Tips
- Inside a macro, use
:.,.+1jointo join the current line with the one below, then continue processing - Combine with
:g::g/^$/,+1joinjoins each blank line with the following line - Use
:joinwith no range to join the current line with the next (equivalent toJin normal mode) - The
!variant matchesgJ: no space is inserted between the joined lines