首页 > 解决方案 > shell排序命令-k POS1,POS2 无效

问题描述

我使用 -k 选项测试排序命令,但我发现 sort -k POS1[,POS2] from POS1 to POS2 无效

$ cat words.txt 
1 1
2 2
2 1
$ sort -k 1 words.txt 
1 1
2 1
2 2
$ sort -k 1,1 words.txt 
1 1
2 1
2 2
我认为“sort -k 1,1 words.txt”应该将结果返回为“cat words.txt”,因为排序只使用第一列,如果第一列相同,则按默认顺序打印。

标签: shellsorting

解决方案


假设您使用的是 GNU sort,您需要指定-s稳定排序的选项。

$ sort --version
sort (GNU coreutils) 8.28
Copyright (C) 2017 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Mike Haertel and Paul Eggert.

$ sort -k 1,1 words.txt
1 1
2 1
2 2

$ sort -k 1,1 -s words.txt
1 1
2 2
2 1

有关详细信息,请参阅该sort实用程序的手册页。


推荐阅读