Sorting lines in Vim

Amongst Vim’s many commands, there’s the humble yet powerful :sort. As you’d expect, it takes a selection or a range and sorts it. By default, that sort is numerical (``through9), then alphabetical (AthroughZfollowed byathroughz).

All that to say that running a generic :sort on the characters to the left in the following example would result in them being reordered to how you see them on the right.

1Original Sorted
2 a => 2
3 B => B
4 c => a
5 2 => b
6 b => c

That’s ever so close to what I’d like. I’d rather it ignore the case of the letters when sorting alphabetically however; something that can easily be done by passing i into the command. :sort i results in the following.

1Original Sorted
2 a => 2
3 B => a
4 c => B
5 2 => b
6 b => c

99% of the time, :sort i is precisely what I’m after. As it’s functionality I use multiple times a day, I have it remapped. <leader>s works well for me.

1xnoremap <leader>s :sort i<cr>

Now for the lesser used, yet still occasionally useful sort options.

:sort! i (no space between the command and the !) will sort the selection in the reverse order:

1Original Sorted
2 a => c
3 B => b
4 c => B
5 2 => a
6 b => 2

:sort u will remove any duplicate lines:

1Original Sorted
2 a => 2
3 B => B
4 b => a
5 c => b
6 2 => c
7 b =>

And :sort n will sort lines based on the first decimal number in the line (use f for a float). In it’s most basic use case (the example below), it will look at the entire value of the number, rather than just the first digit in the number. Otherwise, 55 would be sorted before 9 as 5 precedes 9.

1Original Sorted
2 22 => 1
3 1 => 5
4 42 => 8
5 5 => 22
6 8 => 42
7 80 => 80

It gets better though, as running :sort n on lines that contain numbers will result in them being ordered based on the first number in the line, no matter where in the line that number is.

1Original Sorted
2The 5 quick brown foxes => jumped over the 2 lazy dogs
3jumped over the 2 lazy dogs => at 4 o'clock in the afternoon
4at 4 o'clock in the afternoon => The 5 quick brown foxes

That concludes coverage of the most useful :sort commands, but not all of them. :help sort has explanations of the rest, should you be curious.