Sort CSV file by multiple columns using the “sort” command

You need to use two options for the sort command:

  • --field-separator (or -t)
  • --key=<start,end> (or -k), to specify the sort key, i.e. which range of columns (start through end index) to sort by. Since you want to sort on 3 columns, you’ll need to specify -k 3 times, for columns 2,2, 1,1, and 3,3.

To put it all together,

sort -t ';' -k 2,2 -k 1,1 -k 3,3

Note that sort can’t handle the situation in which fields contain the separator, even if it’s escaped or quoted.

Also note: this is an old question, which belongs on UNIX.SE, and was also asked there a year later.


Old answer: depending on your system’s version of sort, the following might also work:

sort --field-separator=";" --key=2,1,3

Or, you might get “stray character in field spec”.

According to the sort manual, if you don’t specify the end column of the sort key, it defaults to the end of the line.

Leave a Comment