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

How do I sort lines in reverse order in Vim?

Answer

:'<,'>sort!

Explanation

Vim's built-in :sort command accepts a ! flag to reverse the sort order, giving you descending-order sorting without any external tool. It works on any line range, including the current visual selection.

How it works

  • :'<,'> — the range automatically inserted when you press : from Visual mode, covering the selected lines
  • sort — Vim's built-in sort command
  • ! — reverses the sort order (descending instead of ascending)

You can also combine flags:

  • :sort! n — reverse numeric sort
  • :sort! i — reverse case-insensitive sort
  • :sort! u — reverse sort, removing duplicate lines
  • :%sort! — reverse-sort the entire file

Example

Start with these lines selected visually:

banana
apple
cherry
date

After :'<,'>sort!:

date
cherry
banana
apple

Tips

  • :sort n sorts numerically (treats leading numbers as the sort key); :sort! n reverses it — handy for ranking lists
  • :sort /pattern/ sorts by the text matched by the pattern, giving you key-based sorting on delimited data
  • For a quick whole-file reverse sort, use :%sort! without entering Visual mode

Next

How do I create command-line aliases so that typos like W are automatically corrected to w?