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

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/m0 moves them to the beginning
  • :g/pattern/m'a moves them after the line marked with a
  • 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

  • :m moves 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

Next

How do I always access my last yanked text regardless of deletes?