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

How do I sort lines in reverse numerical order in Vim?

Answer

:sort! n

Explanation

The :sort! n command sorts the lines of a buffer (or a range) by their numeric value in descending order. This is the combination of two sort flags: ! to reverse the order, and n to compare values numerically rather than lexicographically — so 10 sorts after 9 instead of before it.

How it works

  • :sort — the Ex sort command
  • ! — reverse the sort order (descending instead of ascending)
  • n — compare by the first numeric value found on each line

Without n, Vim sorts lexicographically, meaning 10 < 2 because '1' < '2' in character order.

Example

Given this buffer:

42
7
100
3
15

After :sort! n:

100
42
15
7
3

Tips

  • Use :'<,'>sort! n to reverse-sort only a visual selection
  • Omit ! for ascending numeric sort: :sort n
  • Add u to remove duplicate values during sorting: :sort! nu
  • Use :sort! f to sort floating-point numbers in descending order (Vim 8+)
  • A range like :2,10sort! n limits sorting to lines 2–10

Next

How do I incrementally expand or shrink a selection based on syntax tree nodes using nvim-treesitter?