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

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

  • :sort is Vim's built-in sort command
  • /regex/ tells :sort to 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 r flag to sort by the matched portion instead: :%sort /pattern/ r
  • Add n for numeric comparison: :%sort /\w*: / n (sort values as numbers)
  • Add i for case-insensitive: :%sort /\w*: / i
  • Reverse with !: :%sort! /\w*: /
  • Works with any range: :'<,'>sort /prefix/ sorts only the visual selection

Next

How do I encode and decode JSON data in Vimscript for configuration and plugin development?