How do I sort lines numerically so that 10 sorts after 2 rather than before it?
Answer
:'<,'>sort n
Explanation
By default, :sort in Vim uses lexicographic (alphabetical) ordering, so "10" sorts before "2" because "1" < "2". Adding the n flag switches to numeric comparison, so numbers are compared by value. This is essential whenever your lines begin with counts, timestamps, version numbers, or any numeric field.
How it works
Select lines in visual mode, then:
:'<,'>sort n— sort selected lines by the leading number, ascending:'<,'>sort n!— sort numerically in descending order:%sort n— sort the entire buffer numerically:'<,'>sort nu— numeric sort, removing duplicate lines
The n flag extracts the first integer found on each line for the comparison key. Non-numeric lines are sorted as if their value were 0.
Example
Starting with:
10 apples
2 bananas
100 cherries
20 dates
After :%sort n:
2 bananas
10 apples
20 dates
100 cherries
With plain :%sort (lexicographic), "10" would have come before "2".
Tips
- Combine flags:
sort nifor case-insensitive numeric sort sort r /pattern/sorts by text that matches the pattern — useful for sorting by a middle column- For floating-point or custom field sorting, pipe through an external sort:
:'<,'>!sort -t, -k2 -n :sortoperates on the range in place — no clipboard or register involved