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

How do I sort lines by a specific column or field in Vim?

Answer

:'<,'>!sort -t',' -k2 -n

Explanation

Vim does not have a built-in multi-column sort, but you can leverage the external sort command to sort selected lines by any field. By piping a visual selection through !sort with the -t (delimiter) and -k (key field) flags, you can sort CSV data, log files, or any structured text by a specific column.

How it works

  • Select the lines you want to sort in visual mode (V for linewise)
  • Type !sort -t',' -k2 -n and press Enter
  • -t',' sets the field delimiter to a comma
  • -k2 sorts by the second field
  • -n uses numeric sorting so 9 comes before 10
  • Vim replaces the selected lines with the sorted output

You can adjust the delimiter and field number for any structured format:

  • !sort -t'\t' -k3 — sort by 3rd tab-separated column
  • !sort -t':' -k2 -n — sort by 2nd colon-separated column numerically
  • !sort -t'|' -k4 -r — sort by 4th pipe-separated column in reverse

Example

Before (CSV data, unsorted):

alice,30,engineering
bob,25,marketing
charlie,35,engineering
dave,28,sales

After selecting all lines and running :'<,'>!sort -t',' -k2 -n:

bob,25,marketing
dave,28,sales
alice,30,engineering
charlie,35,engineering

Tips

  • Remove -n for lexicographic (alphabetical) sorting instead of numeric
  • Add -r to reverse the sort order
  • Use -k2,2 to sort strictly by the second field only (not from field 2 to end of line)
  • For Vim's built-in :sort command, you can sort by a pattern match using :sort /regex/ but it is limited to sorting by what follows the match

Next

How do I use PCRE-style regex in Vim without escaping every special character?