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

How do I sort selected lines numerically in visual mode using the first number on each line?

Answer

:'<,'>sort n /\d\+/

Explanation

Plain :sort n is useful, but it only works when the numeric key starts at the beginning of each line. In real data, numbers are often embedded after labels. Adding a search pattern to :sort lets Vim extract the first matching number per line as the sort key, while still operating only on the visual range.

How it works

  • :'<,'> targets exactly the current visual selection
  • sort n performs numeric sorting instead of lexicographic sorting
  • /\d\+/ tells Vim which text to use as the sort key on each line (the first number found)
  • Lines without a numeric match keep stable behavior relative to the selected range rules

Example

Select the block and run:

:'<,'>sort n /\d\+/

Input:

build-12 status=ok
build-3 status=ok
build-101 status=warn
build-20 status=ok

Output:

build-3 status=ok
build-12 status=ok
build-20 status=ok
build-101 status=warn

Tips

  • For decimal numbers, refine the key pattern (for example /\d\+\.\d\+/).
  • Use :'<,'>sort! n /\d\+/ to reverse numeric order.
  • This works well after block-selecting log snippets where numeric IDs are not column-aligned.

Next

How do I jump to a literal search target without adding jump-list noise?