How do I duplicate every line matching a pattern, placing a copy directly below each one?
Answer
:g/pattern/t.
Explanation
Combining :global with the :t (copy) command and the . address creates a powerful one-liner: for every line matching a pattern, a copy is inserted immediately below it. Unlike :g/pattern/t$ which moves all matches to the end of the file, t. keeps each copy in context right next to the original.
How it works
:g/patternmarks every line that matches the patternt.means "copy the current line to after line." — and.here refers to the current matched line itself- So each matched line is duplicated directly below itself
- Vim marks all lines before any edits begin, so newly inserted copies are never re-processed
Example
function foo() {}
let x = 1;
function bar() {}
After :g/^function/t.:
function foo() {}
function foo() {}
let x = 1;
function bar() {}
function bar() {}
Tips
- To place the copy above the original instead, use
t.-1(insert before the current line) - Useful as a "safety copy" before bulk edits: duplicate matching lines, then modify the originals while keeping the untouched copies nearby
- Combine with a substitute on the next line:
:g/^TODO/t. | +s/^TODO/DONE/duplicates each TODO line then marks the original as DONE