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

How do I sort lines while ignoring a leading prefix like a key or label?

Answer

:sort /pattern/

Explanation

The :sort /{pattern}/ command sorts lines by their content after the first match of the pattern. This lets you skip a fixed prefix (like a status label or key name) so lines are ordered by the meaningful part.

How it works

  • :sort sorts all lines in the buffer (or a range)
  • The /{pattern}/ argument acts as a skip prefix — Vim finds the first match of the pattern on each line and sorts by everything that follows it
  • Without the r flag, the matched text itself is excluded from comparison; only the text after it is used

Example

Given these lines:

TODO: Refactor auth module
DONE: Add unit tests
TODO: Fix null pointer bug
DONE: Update dependencies

Running :%sort /\S\+:\s/ sorts by the task text after the STATUS: prefix:

DONE: Add unit tests
TODO: Fix null pointer bug
DONE: Update dependencies
TODO: Refactor auth module

The pattern \S\+:\s matches one or more non-whitespace characters followed by : , effectively skipping the status label.

Tips

  • Combine with the i flag for case-insensitive skip-prefix sorting: :sort i /prefix/
  • Use the r flag to sort by the matched text instead of after it: :sort r /\w\+$/ sorts by the last word
  • Apply to a range: :'<,'>sort /prefix/ to sort only selected lines
  • The skip pattern is greedy — it skips the first match on each line

Next

How do I open the directory containing the current file in netrw from within Vim?