Sort lines by group and column

ぃ、小莉子 提交于 2020-01-25 20:56:31

问题


I have a csv file separated by semicolons. Which contains lines as shown below.. And I need to sort it by the first and third column, respecting the groups of lines defined by the value of the first column.

booke;book;2
booke;booke;1
booke;bookede;6
booke;bookedes;8
booke;booker;4
booke;bookes;7
booke;booket;3
booking;booking;1
booking;bookingen;2
booking;bookingens;3
booking;bookinger;7
booking;bookingerne;5
booking;bookingernes;6
booking;bookingers;8
booking;bookings;4

Expected output:

booke;booke;1
booke;book;2
booke;booket;3
booke;booker;4
booke;bookede;6
booke;bookes;7
booke;bookedes;8
booking;booking;1
booking;bookingen;2
booking;bookingens;3
booking;bookings;4
booking;bookingerne;5
booking;bookingernes;6
booking;bookinger;7
booking;bookingers;8

I tried it with sort -t; -k3,3n -k1,1 but it's sorted by the third entire column.


回答1:


What about using two sorts in a pipeline fashion:

sort -t ';' -k 3,3n | sort -t ';' -k 1,1 -s

The -s in the second parameter is necessary in order to enable stable sort. Otherwise it could destroy the previous (third column) sorting.

EDIT: however as @BenjaminW. points out in his comment, you can use multiple -k flags, you only specified them the wrong way. By performing a sort:

sort -t ';' -k 1,1 -k 3,3n

It takes the first column als primary sorting column and the third as secondary.



来源:https://stackoverflow.com/questions/34581530/sort-lines-by-group-and-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!