Sort CSV file by column priority using the “sort” command

前端 未结 4 399
自闭症患者
自闭症患者 2020-12-07 12:21

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 t

4条回答
  •  我在风中等你
    2020-12-07 12:50

    Suppose you have another row 3;10;3 in your unsorted.csv file. Then I guess you expect a numerically sorted result:

    2;1;3
    3;1;2
    1;2;3
    3;2;1
    1;3;2
    2;3;1
    3;10;3
    

    and not an alphabetically sorted one:

    2;1;3
    3;1;2
    3;10;3
    1;2;3
    3;2;1
    1;3;2
    2;3;1
    

    To get that, you have to use -n:

    sort --field-separator=';' -n -k 2,2 -k 1,1 -k 3,3 unsorted.csv
    

    It is worth mentioning that 2,2 has to be used. If only 2 is used, then sort takes the string from beginning of field 2 to the end. 2,2 makes sure that only field 2 is used.

提交回复
热议问题