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 (
Vfor linewise) - Type
!sort -t',' -k2 -nand press Enter -t','sets the field delimiter to a comma-k2sorts by the second field-nuses numeric sorting so9comes before10- 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
-nfor lexicographic (alphabetical) sorting instead of numeric - Add
-rto reverse the sort order - Use
-k2,2to sort strictly by the second field only (not from field 2 to end of line) - For Vim's built-in
:sortcommand, you can sort by a pattern match using:sort /regex/but it is limited to sorting by what follows the match