How do I reverse the order of lines in a file or selection?
Answer
:%!tac
Explanation
Vim doesn't have a built-in reverse command, but you can pipe the buffer through tac (reverse of cat) to flip line order. For systems without tac, Vim's :g command offers a pure-Vim alternative.
How it works
:%!tac— reverse all lines using the externaltaccommand:'<,'>!tac— reverse only selected lines- Pure Vim alternative:
:g/^/m0— moves each line to the top, effectively reversing
Example
Before:
line 1
line 2
line 3
line 4
After :%!tac:
line 4
line 3
line 2
line 1
Tips
:g/^/m0is the portable Vim-only solution (works everywhere)- For macOS, use
tail -rinstead oftac(not installed by default) - Reverse a range:
:10,20g/^/m9reverses lines 10-20 - Combine with sort:
:%!sort -rfor reverse-sorted lines