Skip to main content
  1. Posts/

Sort lines based on a column in Vim/Nvim

··231 words·2 mins·
Table of Contents

I have a file where each line has several comma-separated items. I want to sort the lines, based on a certain column. How do we do it inside Vim/Nvim?

There are two different ways to achieve this.

Using external sort

The first is via external tool sort and the vim filter feature (see :help filter). The syntax is:


Lines in the given {range} are sent to external program and are replaced with the output of external command.

For example, to sort the following lines based on the 3rd column:


we can use the following vim command:

:%!sort -t, -k3
" or use the following
" :1,$!sort -t, -k3

Using :sort command

The second method is to use the vim builtin :sort command (see :h :sort for the details).

:sort f /\v^(.{-},){2}/

Explanation of the command:

  • :sort: you can prefix it with a range, like 1,3sort. Without a range, the whole buffer is used (i.e., %sort).
  • f: we are going to sort float numbers. We can also use x (hex number), b (binary number), o (octal number) etc.
  • /\v^(.{-},){2}/: the pattern we are going to skip during sort, i.e., content after the pattern will be sorted.

The default is to sort the lines in ascending order. To sort the lines in descending order, add a ! after :sort (i.e., use :sort!).



A Beginner's Guide on Creating Your Own Text Objects from Scratch in Neovim/Vim
··1234 words·6 mins
How to Insert Unicode Characters in Neovim/Vim
··697 words·4 mins
Search and Replace in Multiple Files in Vim/Neovim
··643 words·4 mins