Vim has built-in sorting command which we can use to sort text , also vim supports invoking external command ,thus we also can use system sort to do so, let’s see some examples.

How to sort in vim alphabetically

:sort

How to sort selected lines in vim

First we can enable line number using command :

:set number

Then to sort selected lines by specifying line number

:2,10 sort

This will sort 2nd line to 10th line.

How to sort descending in vim

:sort!

Note : there is no space between sort and !

How to do unique sort in vim

:sort u

How to sort in vim case-intensive

:sort i

Numeric sort in vim

:sort n

How to sort by column in vim

:%!sort -k2

This uses external system sort utility to sort all lines by the 2nd column , by default the field-separator is space.

To sort by column using specific field separator:

:%!sort -t ':' -k3

Here use : as field separator to sort by column number 3.

How to sort by line length in vim

:1,$  ! awk '{ print length(), $0 | "sort -n | cut -d\\  -f2-" }'
  • 1,$ stands for from 1st line the last line, you can specify your owns

You may also have interest to vim cheat sheet