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! ifor reverse case-insensitive sort;:'<,'>sort! nfor reverse numeric sort (so 10 comes before 2) - Add
uto remove duplicates::'<,'>sort! u - Without the
!,:'<,'>sortsorts in ascending order - Works on the entire file too:
:%sort!reverses the sort for all lines - Use
:'<,'>!sort -rto shell out to the system sort for more control