按升序对多列进行排序

时间:2017-10-19 08:50:20

标签: sorting unix

来源:

10,10,7.17,1.077383,0.00428382
10,12,7.45,1.177068,0.00390197
10,4,6.86,1.184806,0.00489828
10,6,6.98,1.106846,0.00463645
10,8,7.09,1.106254,0.00451672
12,10,6.71,1.224453,0.00506310
12,12,6.96,1.141856,0.00446641
12,4,6.41,1.510563,0.00590838
12,6,6.51,1.187841,0.00548915
12,8,6.62,1.217152,0.00532222

期望的结果

10,4,6.86,1.184806,0.00489828
10,6,6.98,1.106846,0.00463645
10,8,7.09,1.106254,0.00451672
10,10,7.17,1.077383,0.00428382
10,12,7.45,1.177068,0.00390197
12,4,6.41,1.510563,0.00590838
12,6,6.51,1.187841,0.00548915
12,8,6.62,1.217152,0.00532222
12,10,6.71,1.224453,0.00506310
12,12,6.96,1.141856,0.00446641

如何对前两列的csv进行排序,以便按升序获得所需的结果。

10,4
10,6
10,8
10,12

sort -k1,2 -n -t,没有按预期工作

10,4,6.86,1.184806,0.00489828
10,6,6.98,1.106846,0.00463645
10,8,7.09,1.106254,0.00451672
12,4,6.41,1.510563,0.00590838
12,6,6.51,1.187841,0.00548915
12,8,6.62,1.217152,0.00532222

您可以看到10,10,7.17,1.077383,0.00428382缺失

2 个答案:

答案 0 :(得分:0)

sort -k1,1 -k2,2 -n -t,工作正常

更多信息:https://unix.stackexchange.com/questions/78925/how-to-sort-by-multiple-columns

答案 1 :(得分:0)

要回答您的问题,您应该使用:

sort -t, -k1,1n -k2,2n yourFile.csv

您的命令的问题是-n不适用于您尝试排序的字段; -k1,2n会这样做,但它不能解决你的问题,因为它会将两个字段一起考虑(例如10,10,10,12),并且可能因为你的语言环境而无法工作。

如果您尝试

LC_ALL=C sort -t, -k1,2n yourFile.csv

你会得到类似的东西:

10,10,7.17,1.077383,0.00428382
10,12,7.45,1.177068,0.00390197
10,4,6.86,1.184806,0.00489828
10,6,6.98,1.106846,0.00463645
10,8,7.09,1.106254,0.00451672
12,10,6.71,1.224453,0.00506310
12,12,6.96,1.141856,0.00446641
12,4,6.41,1.510563,0.00590838
12,6,6.51,1.187841,0.00548915
12,8,6.62,1.217152,0.00532222

(由前两个字段'连接'排序)。