我怎么能对第一列进行排序,然后用“排序”的第二个数字排序?

时间:2023-01-21 21:31:18

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 file sorts by the second column.

按第一列排序,但不按第二列排序。运行的只是按第二列排序-k2n文件。

b 1
a 2
a 10

How could I sort it by two columns?

我怎么能把它分成两列呢?

Edit:

sort (GNU coreutils) 5.93

(GNU coreutils)5.93

3 个解决方案

#1


24  

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

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

sort -k1,1 -k2n

#2


7  

It is almost correct. Try this:

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

sort -k1,1 -k2,2n

#3


5  

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

如果你有GNU排序,你可以做一个版本排序:

$ 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

#1


24  

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

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

sort -k1,1 -k2n

#2


7  

It is almost correct. Try this:

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

sort -k1,1 -k2,2n

#3


5  

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

如果你有GNU排序,你可以做一个版本排序:

$ 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