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

How do I sort lines by a field in the middle or end of each line using a pattern?

Answer

:sort r /\w\+$/

Explanation

The :sort r /{pattern}/ command sorts lines using the text that matches the pattern as the sort key. Without the r flag, Vim skips the matched portion and sorts by the text that follows it. With r, Vim sorts BY the match itself — making it possible to sort by any field in a line, not just the beginning.

How it works

  • :sort /{pattern}/ — sort key is the text after the match (skips the match)
  • :sort r /{pattern}/ — sort key is the text matching the pattern
  • Combine flags: :sort nr /{pattern}/ for numeric sort by match
  • Combine flags: :sort ir /{pattern}/ for case-insensitive sort by match

Example

Given these lines:

cherry pie
apple tart
banana split

Running :sort r /\w\+$/ sorts by the last word on each line (pie, tart, split), producing:

cherry pie
banana split
apple tart

Without r, :sort /\w\+$/ sorts by text after the last word — which is empty for all lines — leaving the order unchanged.

Tips

  • Sort log lines by severity in brackets: :sort r /\[\u\l\+\]/
  • Sort key=value lines by value (without r): :sort /\w\+=/ — skips key=, sorts by value
  • Sort by a middle numeric field: :sort nr /: \d\+/ where the pattern matches the number field
  • Use :sort! (with !) to reverse the final order

Next

How do I delete all lines matching my last search pattern without retyping it?