How do I sort lines by their numeric value instead of alphabetically?
Answer
:sort n
Explanation
:sort n sorts lines by the first number found on each line, comparing values numerically rather than as strings. Without the n flag, Vim sorts lexicographically, so 9 sorts after 10 because '9' > '1'. Adding n fixes this by treating the leading number as an integer.
How it works
:sort— lexicographic (alphabetical) sort:sort n— numerical sort by the first integer on each line:sort! n— numerical sort, descending:'<,'>sort n— sort only the visually selected lines numerically
Example
Before (lexicographic :sort would give wrong order):
2 apples
10 bananas
1 cherry
20 dates
After :sort n:
1 cherry
2 apples
10 bananas
20 dates
Tips
:sort uremoves duplicate lines while sorting (combine::sort nufor numerical + unique):sort imakes the sort case-insensitive:sort! nreverses the order (largest first)- For floating-point numbers, use
:sort finstead of:sort n