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 matchingregexand sorts on what comes after:sort r /regex/— sorts on the text that matchesregex- Combine with
nfor numeric sort::sort rn /\d\+/sorts by the first number on each line - Combine with
ifor 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
%sortto sort the whole file or'<,'>sortfor a visual selection - Add
!to reverse the sort order::sort! r /pattern/ - Combine with
uto remove duplicate lines after sorting::sort ru /pattern/ - The
\zsanchor inside the pattern controls exactly where the match key starts