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

How do I sort lines based on a specific column or pattern match rather than the whole line?

Answer

:%sort /[^,]*,/ n

Explanation

Vim's :sort command accepts a pattern that controls which part of each line is used as the sort key. The text after the pattern match becomes the sort key. Combined with the n flag for numeric sorting, this lets you sort structured data by any field or column.

How it works

  • :%sort — sort all lines in the buffer
  • /[^,]*,/ — a pattern matching everything up to and including the first comma (the first field)
  • n — sort numerically by what follows the match (the second field)

Vim finds the pattern on each line, skips past it, and sorts by the remaining text.

Example

Given a CSV-like file:

alice,30,engineer
bob,25,designer
carol,35,manager

Sort by the second column (numerically):

:%sort /[^,]*,/ n

Result:

bob,25,designer
alice,30,engineer
carol,35,manager

Tips

  • Use the r flag to sort by the matched text itself instead of what follows: :%sort /\d\+/ rn
  • Add i for case-insensitive sorting: :%sort /pattern/ i
  • Use ! to reverse the sort order: :%sort! /[^,]*,/ n
  • Works with visual selections too: :'<,'>sort /pattern/ n
  • Skip multiple fields by repeating the pattern: :%sort /\([^,]*,\)\{2\}/ n sorts by the third field

Next

How do I ignore whitespace changes when using Vim's diff mode?