Gregg's MOTD

Tips & Tricks that I've Encountered Over the Years...

Sorting Stuff in the VIM Buffer

August 07, 2023 — Gregg Szumowski

Suppose I have a file that I am editing in vim with the following contents:

$ cat file.txt
Red 4
Blue 3
Green 1
Orange 7
Black 8
Yellow 6
Purple 2
White 5

If I want to sort this data in vim, the first thing to do is to format it into columns using the column command:

:%!column -t

Which will put the data in the following format:

Red 4
Blue 3
Green 1
Orange 7
Black 8
Yellow 6
Purple 2
White 5

Then we can sort on the 2nd column using the sort command:

:%!sort -k2nr

Which will update the buffer like this:

Black 8
Orange 7
Yellow 6
White 5
Red 4
Blue 3
Purple 2
Green 1

Tags: cli, vim, sort, motd