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

How do I move all lines matching a pattern to the top of the file?

Answer

:g/pattern/m0

Explanation

When working with large files, you sometimes need to reorganize content by pulling all lines matching a certain pattern to the top. The :g/pattern/m0 command combines the global command with the move command to do exactly this in a single operation.

How it works

  • :g/pattern/ — the global command matches every line containing pattern
  • m0 — the move command relocates each matched line to after line 0 (i.e., the very top of the file)

Because :g processes lines from top to bottom, each successive match is moved to line 1, pushing the previous one down. The result is that matching lines appear at the top in reverse order relative to their original positions. If you want to preserve the original order, use :g/pattern/m$ to move them to the end instead, or pipe through a two-pass approach.

Example

Given a file:

apple
banana
cherry TODO
date
elderberry TODO
fig

Running :g/TODO/m0 produces:

elderberry TODO
cherry TODO
apple
banana
date
fig

The two TODO lines are now at the top (in reverse order).

Tips

  • Use :g/TODO/m$ to send matching lines to the bottom instead
  • Combine with :v (inverse global) to move non-matching lines: :v/keep/m$
  • This works great for sorting imports, gathering TODOs, or triaging log lines

Next

How do I ignore whitespace changes when using Vim's diff mode?