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:globalcommand executes a command on every line matching the pattern.^matches every linem 0— the:movecommand 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 4reverses lines 5 through 10 - Combine with
:sortif you need to sort and then reverse (:sort!sorts in reverse order directly) - This is a single undo step — press
uto restore the original order instantly