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

How do I sort lines using only the text matched by a regex pattern as the sort key?

Answer

:sort /regex/ r

Explanation

Vim's :sort command supports an r flag that changes how a pattern affects sorting. By default, :sort /pattern/ skips the matched portion and sorts by the text that follows it. With the r flag, :sort /pattern/ r sorts lines using only the matched text as the sort key.

How it works

  • :sort /pattern/ — sort by the text after the pattern match (skips matched portion)
  • :sort /pattern/ r — sort by the text of the pattern match itself
  • :sort /pattern/ rn — sort by the matched text numerically (n flag)
  • :sort /pattern/ ri — sort by the matched text case-insensitively (i flag)

Note: when used without a pattern, r simply reverses the sort order. The special behavior (sort by match) only applies when combined with /pattern/.

Example

Given lines with varying numbers at the end:

foo 30
baz 5
bar 20

To sort by the trailing number:

:%sort /\d\+$/ rn

Result:

baz 5
bar 20
foo 30

Another use — sort log entries by severity:

:%sort /\(ERROR\|WARN\|INFO\)/ r

This groups lines by their log level (ERROR, INFO, WARN alphabetically).

Tips

  • Combine r with u to sort by match and remove duplicate-keyed lines: :sort /pattern/ ru
  • Use a visual selection range to sort only part of the file: :'<,'>sort /pattern/ r
  • For reverse sort without a pattern, use :sort! (the ! reverses order)

Next

How do I hard-wrap the current paragraph to the textwidth in Vim?