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

How do I reverse the order of all lines in a file using Vim?

Answer

:g/^/m 0

Explanation

This clever use of the :global command reverses every line in the current buffer. It works by matching every line (using the pattern ^, which matches the start of any line) and moving each one to the top of the file. As each successive line is moved to line 0, the original order is inverted.

How it works

  • :g/^/ — the :global command executes a command on every line matching the pattern. ^ matches every line
  • m 0 — the :move command relocates the current line to after line 0 (i.e., the very top of the file)

As :global processes lines from top to bottom, each line gets moved to the top, effectively reversing the entire file.

Example

Before:

alpha
beta
gamma
delta

After running :g/^/m 0:

delta
gamma
beta
alpha

Tips

  • To reverse only a range, use :{start},{end}g/^/m {start-1} — for example, :5,10g/^/m 4 reverses lines 5 through 10
  • Combine with :sort if you need to sort and then reverse (:sort! sorts in reverse order directly)
  • This is a single undo step — press u to restore the original order instantly

Next

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