csvkit

Using csvkit to sort on multiple columns, reverse order for some


I am using csvsort from csvkit to sort my csv data. I'd like to sort based on two columns, one of which should be in reverse order. Is that possible?

For example:

echo 'v1,v2,v3
      a,1,z
      b,3,x
      c,2,y
      a,2,y
      b,1,x
      c,3,z' | csvsort -c1,2 |csvlook

gives

| v1 | v2 | v3 |
| -- | -- | -- |
| a  |  1 | z  |
| a  |  2 | y  |
| b  |  1 | x  |
| b  |  3 | x  |
| c  |  2 | y  |
| c  |  3 | z  |,

but I want

| v1 | v2 | v3 |
| -- | -- | -- |
| a  |  2 | z  |
| a  |  1 | y  |
| b  |  3 | x  |
| b  |  1 | x  |
| c  |  3 | y  |
| c  |  2 | z  |.

csvsort -r -c1,2 reverses order on both columns. csvsort -rc 1 -c 2 sorts only on column 2 (in reverse, so the same as csvsort -rc 2).


Solution

  • the way with csvkit is

    csvsql --query "select * from input order by v1, v2 desc" input.csv
    

    it gives you

    v1 v2 v3
    a  2  y
    a  1  z
    b  3  x
    b  1  x
    c  3  z
    c  2  y