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

How do I sort lines by the text that matches a regex pattern rather than the text after it?

Answer

:sort r /pattern/

Explanation

The :sort r /pattern/ command sorts lines using the matched portion of the regex as the sort key. By default, :sort /pattern/ skips past the match and sorts on what follows — the r flag reverses this, making the matching text itself the key.

How it works

  • :sort /regex/ — skips text matching regex and sorts on what comes after
  • :sort r /regex/ — sorts on the text that matches regex
  • Combine with n for numeric sort: :sort rn /\d\+/ sorts by the first number on each line
  • Combine with i for case-insensitive: :sort ri /\w\+/

Example

Given these task lines:

Task A: priority 3
Task C: priority 1
Task B: priority 2

Running :sort rn /\d\+/ sorts numerically by the matched number:

Task C: priority 1
Task B: priority 2
Task A: priority 3

Without the r flag, :sort n /priority / would sort by the text after priority — producing the same result here, but :sort r is essential when the key you want to sort by is the matched text itself (not what follows it).

Tips

  • Use %sort to sort the whole file or '<,'>sort for a visual selection
  • Add ! to reverse the sort order: :sort! r /pattern/
  • Combine with u to remove duplicate lines after sorting: :sort ru /pattern/
  • The \zs anchor inside the pattern controls exactly where the match key starts

Next

How do I stop Vim from automatically continuing comment markers when I press Enter or open a new line?