How to sort a file in unix both alphabetically and numerically on different fields?

↘锁芯ラ 提交于 2021-02-05 17:58:19

问题


Please don't think this is a repeat of the "Sorting alphanumeric data in unix" question... I looked at the other answers, and think my case is a bit different!

I have data like this:

A    192
D    112
D    188
C    091
A    281
B    919

...And I want to sort first column 1 (alphabetically), and then by column 2 (numerically). I tried using:

sort -n -k1,2

...But this gave me correctly sorted for the first field, but then the wrong sorting for the second field (1000,1002,1003,10,1 ... instead of 1,10,1000,1002,1003).

Can someone please suggest how to sort these two columns the way I'd like?


回答1:


Try using like this:-

sort -k1,1 -k4,4n
  • -n : Makes the program sort according to numerical value
  • -k opts: Sort data / fields using the given column number. For example, the option -k 2 made the program sort using the second
    column of data. The option -k 3,3n -k 4,4n sorts each column. First
    it will sort 3rd column and then 4th column.



回答2:


This should work:

sort -t "," -k1,1 -k2n,2 file


来源:https://stackoverflow.com/questions/18193392/how-to-sort-a-file-in-unix-both-alphabetically-and-numerically-on-different-fiel

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