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

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

Answer

:g/^/m0

Explanation

The :g/^/m0 command is a clever use of Vim's global command to reverse every line in the file. It processes each line top-to-bottom and moves it to the top, which naturally reverses the entire file.

How it works

  • :g is the global command — it executes a command on every line matching a pattern
  • /^/ matches every line (since every line has a beginning)
  • m0 moves the current line to after line 0 (i.e., the top of the file)

As :g processes lines from top to bottom, line 1 goes to the top first, then line 2 goes above it, then line 3 above that, and so on — effectively reversing the order.

Example

Given the text:

alpha
beta
gamma
delta

After running :g/^/m0:

delta
gamma
beta
alpha

Tips

  • To reverse only a range, use :'<,'>g/^/m'< on a visual selection
  • Combine with :sort if you need the reverse of a sorted list: :sort then :g/^/m0
  • You can also reverse with the external command :%!tac on Linux or :%!tail -r on macOS
  • Use u to undo if the result isn't what you expected

Next

How do I edit multiple lines at once using multiple cursors in Vim?