I have a csv file, and I would like to sort it by column priority, like "order by". For example:
3;1;2 1;3;2 1;2;3 2;3;1 2;1;3 3;2;1
If this situation was the result of a "select", the "order by" would be as follows: order by 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 "sort" command on Unix.
To sort CSV by multiple columns, use the sort_values() method. Sorting by multiple columns means if one of the columns has repeated values, then the sort order depends on the 2nd column mentioned under sort_values() method.
To sort by a delimiter pass the -t option to sort along with the delimiter value. For a CSV file this would be , . This can be combined with the -k option to sort on fields within a CSV. The result will be written to standard output.
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 .
Use the -k option to sort on a certain column. For example, use " -k 2 " to sort on the second column.
sort --field-separator=';' --key=2,1,3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With