Brendan Dawes
The Art of Form and Code

Sorting a CSV File With Vim

This is just a quickie but I wanted to make a note as it can come in handy.

I had a csv file detailing population density for various cities around the world which looked like this:

1,Tokyo,Japan,33200000,6993,4750
2,New York,USA,17800000,8683,2050
3,Sao Paulo,Brazil,17700000,1968,9000
4,Seoul,South Korea,17500000,1049,16700
5,Mexico City,Mexico,17400000,2072,8400
6,Kyoto,Japan,16425000,2564,6400
7,Manila,Philippines,14750000,1399,10550
8,Mumbai,India,14350000,484,29650
9,Delhi,India,14300000,1295,11050
10,Jakarta,Indonesia,14250000,1360,10500
11,Lagos,Nigeria,13400000,738,18150
12,Kolkata,India,12700000,531,23900
13,Cairo,Egypt,12200000,1295,9400
14,Los Angeles,USA,11789000,4320,2750
15,Buenos Aires,Argentina,11200000,2266,4950
16,Rio de Janeiro,Brazil,10800000,1580,6850
17,Moscow,Russia,10500000,2150,4900
18,Shanghai,China,10000000,746,13400
19,Karachi,Pakistan,9800000,518,18900
20,Paris,France,9645000,2723,355
...

It's ordered by rank of population density and for something I was creating (populating a menu), I needed this list in alphabetical order.

To do that I used the Unix sort command directly in Vim.

Pressing V I went into visual line mode and pressed G to select the whole document.

Then I pressed : so I could execute a command on those selected lines.

To sort the csv file using the second column as a key — the city name — I then typed this command and hit return:

!sort -k 2 -t ,

This executes the external Unix sort command. The -k flag stipulates which column to sort on — in our case number 2, whilst the -t flag specifies the delimiter to use.

Now the csv file was correctly sorted:

125,Accra,Ghana,1500000,453,3300
70,Ankara,Turkey,3100000,583,5300
61,Athens,Greece,3685000,684,5400
64,Atlanta,USA,3500000,5083,700
35,Baghdad,Iraq,5500000,596,9250
94,Baku/Sumqayit,Azerbaijan,2100000,544,3850
96,Baltimore,USA,2076000,1768,1150
37,Bangalore,India,5400000,534,10100
31,Bangkok,Thailand,6500000,1010,6450
59,Barcelona,Spain,3900000,803,4850
23,Beijing,China,8614000,748,11500
107,Beirut,Lebanon,1800000,648,2800
53,Belo Horizonte,Brazil,4000000,868,4600
62,Berlin,Germany,3675000,984,3750
86,Birmingham,UK,2284000,600,3800
29,Bogota,Colombia,7000000,518,13500
52,Boston,USA,4032000,4497,900
113,Brasilia,Brazil,1625000,583,2800
122,Brisbane,Australia,1508000,1603,950
117,Brussels,Belgium,1570000,712,2200
108,Budapest,Hungary,1800000,702,2550
15,Buenos Aires,Argentina,11200000,2266,4950
13,Cairo,Egypt,12200000,1295,9400
111,Campinas,Brazil,1750000,492,3550
78,Cape Town,South Africa,2700000,686,395