sort -k选项的注意事项

转自:linuxtone 作者:iytsse

-k选项使用有一个潜规则,如果不注意排序是不对的。
举个例子,以下内容保存为fruit:
apple 4
apple 5
第一个字段为水果名称,第二个字段为价格。我的需求是,首先对水果名称进行排序,然后再根据价格进行降序。我的第一反应是:


Shell代码

  1. cat fruit|sort -k1 -k2nr


cat fruit|sort -k1 -k2nr结果是什么?居然还是:
apple 4
apple 5
正确的命令应该是:



Shell代码

  • cat fruit|sort -k1,1 -k2nr


  • cat fruit|sort -k1,1 -k2nr这样的结果才正确:
    apple 5
    apple 4
    查看sort -k说明:



    Shell代码

  • -k POS1[,POS2]

  • –key=POS1[,POS2]
  • Specify a sort field that consists of the part of the line between
  • POS1 and POS2 (or the end of the line, if POS2 is omitted)

  • -k POS1[,POS2] –key=POS1[,POS2] Specify a sort field that consists of the part of the line between POS1 and POS2 (or the end of the line, if POS2 is omitted)意思是如果省略了POS2,那么排序字段的end就会设定为行尾。太奇怪的规则了,这样很容易让人误用。
    回到刚才的例子,使用awk -k1的后果是,第一个排序字段的内容延长到行尾,包括了价格,使得-k2nr的作用完全失效。
    初次使用sort要注意这个潜规则,很无语。