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 matchespatternjoin— 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/,+1joinjoins 2 lines (the match plus 1 more)