I have a CSV-like file, and I would like to sort it by column priority, like "ORDER BY" in SQL. For example, given the following rows,
3;1;2
1;3;2
1;2;3
2;3;1
2;1;3
3;2;1
If "ORDER BY" were column2, column1, column3
, the result would be:
2;1;3
3;1;2
1;2;3
3;2;1
1;3;2
2;3;1
I'd like to know how to get this same result using the sort
command on Unix.
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.