csvkit icon indicating copy to clipboard operation
csvkit copied to clipboard

csvsort: ascending sort for some columns, descending for others

Open danmichaelo opened this issue 8 years ago • 4 comments

csvsort is great, but would be even better if you could combine ascending and descending sort. Columns prefixed with a minus sign could be sorted descending. Like so:

csvsort -c 1,2,-3

to sort by column 1 ascending, 2 ascending and 3 descending.

danmichaelo avatar Feb 08 '18 23:02 danmichaelo

Was just looking as csvkit and hit the same issue - need to order ascending on two columns - then descending on a third.

donmullen avatar Mar 12 '18 17:03 donmullen

We'd have to use functools.cmp_to_key as the basic key function can't switch order for different columns.

jpmckinney avatar Feb 15 '24 17:02 jpmckinney

So a problem with specifying "-3" is that this is interpreted as "the range from the first column up to 3", same as the cut command. We can maybe use ~ if that seems intuitive.

jpmckinney avatar Feb 15 '24 18:02 jpmckinney

As an option, we can use csvsql:

$ csvsql --query "SELECT * FROM YourFile ORDER BY C1 ASC, C2 ASC, C3 DESC" YourFile.csv

Kjuly avatar Jun 24 '24 23:06 Kjuly