How do I sort lines by a secondary field while ignoring a common leading prefix?
Answer
:[range]sort /regex/
Explanation
The :[range]sort /regex/ command sorts lines while skipping the portion of each line that matches the regex. This makes the text after the match the effective sort key — perfect when a leading prefix would otherwise dominate the ordering.
How it works
:sortis Vim's built-in sort command/regex/tells:sortto skip any text matching the pattern at the start of each line- The actual sort key becomes everything after the matched prefix
- Without a pattern, the entire line determines the order
Example
Given these key: value lines:
z_lang: Python
a_lang: Ruby
m_lang: Go
Running :%sort /\w*: / (skip word: prefix) produces:
m_lang: Go
z_lang: Python
a_lang: Ruby
The sort key is the value after the colon — Go, Python, Ruby — not the key name.
Tips
- Add the
rflag to sort by the matched portion instead::%sort /pattern/ r - Add
nfor numeric comparison::%sort /\w*: / n(sort values as numbers) - Add
ifor case-insensitive::%sort /\w*: / i - Reverse with
!::%sort! /\w*: / - Works with any range:
:'<,'>sort /prefix/sorts only the visual selection