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

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 (like gJ in 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 as J in 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 :.,.+1join to join the current line with the one below, then continue processing
  • Combine with :g: :g/^$/,+1join joins each blank line with the following line
  • Use :join with no range to join the current line with the next (equivalent to J in normal mode)
  • The ! variant matches gJ: no space is inserted between the joined lines

Next

How do I stop Vim from automatically continuing comment markers when I press Enter or open a new line?