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

How do I sort lines based on a specific field or column rather than the beginning of each line?

Answer

:sort /regex/

Explanation

The :sort /pattern/ command sorts lines by the text that appears after the first match of a pattern, not from the start of each line. This lets you sort by any field — a second column, a value after a delimiter, a trailing number — without needing an external tool like sort -k.

How it works

  • :sort /pattern/ — each line is effectively sorted by everything after the pattern match
  • The matched portion is "skipped" for comparison purposes; the key is what follows the match
  • Combine with flags:
    • n — sort the remaining text numerically
    • r — reverse the sort order
    • i — case-insensitive sort

Example

Given a list of name–score pairs:

bob     42
alice   7
charlie 115
dave    3

Sort numerically by the score (the field after the word and whitespace):

:%sort n /\w\+\s\+/

Result:

dave    3
alice   7
bob     42
charlie 115

For CSV, sort by the second column:

:%sort /[^,]*,/

Tips

  • Combine with a visual selection to sort only a subset of lines: :'<,'>sort n /\w\+\s\+/
  • :sort u /pattern/ (unique) removes duplicate sort keys after sorting
  • If no match is found on a line, that line is sorted by its full text — so non-matching lines float to a predictable position
  • For multi-key sorts (sort by field 2, then field 3), you need external tools; for single-field sorts in Vim, this is the most powerful built-in approach

Next

How do I define or modify a macro directly as a string without recording it?