How do I move all lines matching a pattern to the end of a file?
Answer
:g/pattern/m$
Explanation
The :g (global) command combined with :m (move) relocates all matching lines to a specified destination. Using $ as the destination moves them to the end of the file.
How it works
:g/pattern/m$moves every matching line to the end of the file:g/pattern/m0moves them to the beginning:g/pattern/m'amoves them after the line marked witha- The moved lines maintain their relative order
Example
Given the text:
alpha
# TODO: fix this
beta
# TODO: add tests
gamma
Running :g/TODO/m$ produces:
alpha
beta
gamma
# TODO: fix this
# TODO: add tests
More examples
" Move all import lines to the top
:g/^import/m0
" Move blank lines to the end (effectively removing gaps)
:g/^$/m$
" Move all matching lines after line 10
:g/pattern/m10
" Copy instead of move
:g/pattern/t$
Tips
:mmoves lines;:t(or:copy) copies them instead- This is non-destructive to the content — it just rearranges line order
- Combine with
:v(inverse match) to move non-matching lines instead - This is far more efficient than manual cut-paste for reorganizing files