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

How do I join every line matching a pattern with the line that follows it?

Answer

:g/pattern/join

Explanation

The :g/pattern/join command combines the :global command with :join to merge every line matching a pattern with the line immediately following it. This is useful for reassembling continuation lines, merging key-value pairs spread across two lines, or collapsing structured data without writing a macro.

How it works

  • :g/pattern/ — runs the following command on every line that matches pattern
  • join — joins the matched line with the line below it (removes the newline between them, inserting a space)

For example, to join lines ending with a backslash (shell continuation lines):

:g/\\$/join

To join lines that start with a label followed by a colon, with the data line beneath them:

:g/^\w\+:/join

Example

Given:

Name:
Alice
Age:
30
City:
Paris

Running :g/:/join produces:

Name: Alice
Age: 30
City: Paris

Tips

  • Use join! to join without inserting a space between lines
  • Combine with a range to limit the operation: :'<,'>g/pattern/join
  • To join N lines together: :g/pattern/,+1join joins 2 lines (the match plus 1 more)

Next

How do I replace only part of a matched pattern using \zs and \ze in a substitution?