Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort CSV file by column priority using the "sort" command

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.

like image 251
Rafael Orágio Avatar asked Feb 27 '12 19:02

Rafael Orágio


People also ask

How do I sort a column in a CSV file using pandas?

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.

How do I sort a CSV file in Unix?

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.

How do I sort a CSV file in Ubuntu?

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 .

How do I sort a column in Linux?

Use the -k option to sort on a certain column. For example, use " -k 2 " to sort on the second column.


1 Answers

sort --field-separator=';' --key=2,1,3 
like image 61
Charlie Martin Avatar answered Sep 22 '22 09:09

Charlie Martin