Linux 如何以文本方式按第一列排序,然后使用“排序”按第二列数字排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14624850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:52:26  来源:igfitidea点击:

How can I sort by first column textually and then by the second numerically with 'sort'?

linuxshellunixsorting

提问by Necto

I'm trying to sort the following file:

我正在尝试对以下文件进行排序:

a 2
b 1
a 10

I need to get:

我需要得到:

a 2
a 10
b 1

I know about the -kPOS[opts] option, and try to use it:

我知道 -kPOS[opts] 选项,并尝试使用它:

sort -k1 -k2n file

but this command gives me only:

但这个命令只给了我:

a 10
a 2
b 1

So it sorts by the first column, but no by the second. Running just sort -k2n filesorts by the second column.

所以它按第一列排序,但不按第二列排序。运行只是sort -k2n file按第二列排序。

b 1
a 2
a 10

How could I sort it by two columns?

我怎么能按两列排序?

Edit:

编辑:

sort (GNU coreutils) 5.93

排序(GNU coreutils)5.93

采纳答案by choroba

You have to terminate the primary key, otherwise, sort uses all the fields starting from the given one:

您必须终止主键,否则, sort 使用从给定字段开始的所有字段:

sort -k1,1 -k2n

回答by Chris Seymour

If you have GNU sortsort then you can do a version sort:

如果您有GNU sort排序,那么您可以进行版本排序:

$ sort -V file
a 2
a 10
b 1

Option:

选项:

-V, --version-sort          natural sort of (version) numbers within text

The nice thing about version sorting is it will work regardless of columns:

版本排序的好处是无论列如何它都可以工作:

$ cat file
a2
b1
a10

$ sort -V file
a2
a10
b1

回答by Magnus Gustavsson

It is almost correct. Try this:

这几乎是正确的。尝试这个:

sort -k1,1 -k2,2n