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

How do I sort lines within a visual selection in reverse alphabetical order?

Answer

:'<,'>sort!

Explanation

The sort! command sorts the selected lines in reverse (descending) order. When you select lines with visual mode and press :, Vim automatically prepends '<,'> to form a range. Adding ! inverts the sort direction, so lines go from Z to A instead of A to Z. This is useful for reversing sorted lists, ordering CSS properties from longest to shortest, or quickly flipping any text that should read in descending sequence.

How it works

  • '<,'> — the Ex command range for the last visual selection (set automatically when you press : in visual mode)
  • sort — sorts the lines in the range lexicographically (alphabetically) by default
  • ! — reverses the sort order, making it descending

Example

With these lines visually selected:

apple
cherry
banana

Running :'<,'>sort! produces:

cherry
banana
apple

Tips

  • Combine flags: :'<,'>sort! i for reverse case-insensitive sort; :'<,'>sort! n for reverse numeric sort (so 10 comes before 2)
  • Add u to remove duplicates: :'<,'>sort! u
  • Without the !, :'<,'>sort sorts in ascending order
  • Works on the entire file too: :%sort! reverses the sort for all lines
  • Use :'<,'>!sort -r to shell out to the system sort for more control

Next

How do I jump to a tag in Vim and automatically choose if there is only one match?