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

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 u removes duplicate lines while sorting (combine: :sort nu for numerical + unique)
  • :sort i makes the sort case-insensitive
  • :sort! n reverses the order (largest first)
  • For floating-point numbers, use :sort f instead of :sort n

Next

How do I make Vim always open new splits below and to the right instead of above and to the left?