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

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 external tac command
  • :'<,'>!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/^/m0 is the portable Vim-only solution (works everywhere)
  • For macOS, use tail -r instead of tac (not installed by default)
  • Reverse a range: :10,20g/^/m9 reverses lines 10-20
  • Combine with sort: :%!sort -r for reverse-sorted lines

Next

How do I return to normal mode from absolutely any mode in Vim?