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
:gis the global command — it executes a command on every line matching a pattern/^/matches every line (since every line has a beginning)m0moves 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
:sortif you need the reverse of a sorted list::sortthen:g/^/m0 - You can also reverse with the external command
:%!tacon Linux or:%!tail -ron macOS - Use
uto undo if the result isn't what you expected