0

如何按 2 个单独的列排序?例如,我想先按第 6 列排序,然后按第 4 列排序

 column4  column5    column6
 lae2894      603    user1
 e2894       2096    user1
 e2894       2096    user1
 e2894       2096    user1
 lae2894      603    user1
 lae2894      603    user1

这些已按以下命令排序:

sort -t, -k6 users.txt > sorted-user.txt

但我想要的输出应该是这样的:

 column4      column5      column6
 e2894            603        user1
 e2894           2096        user1
 e2894           2096        user1
 laee2894        2096        user1
 lae2894          603        user1
 lae2894          603        user1
4

2 回答 2

1

大多数版本sort允许多个关键规范。尝试这个:

sort -t, -k6,6 -k4,4 input.txt

我假设您的实际输入文件,用作分隔符,因为您在示例命令中指定了这一点(这意味着您粘贴的“示例”数据并不真正代表您的文件......)。另请注意,只有一个数字的键规范(如您的-k6)表示从该字段开始并延伸到行尾的单个键,因此为了指定要排序的单个字段,您需要使用语法以上。

于 2013-06-25T14:53:01.790 回答
1

-k选项sort可以出现多次。尝试:

sort -t, -k6,6 -k4,4 inputfile

有关更多信息,请参阅排序调用

> ‘-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), inclusive. 
Each pos has the form ‘f[.c][opts]’, where f is the number of the field to use, and c is the number of the first character from the beginning of the field. Fields and character positions are numbered starting with 1; a character position of zero in pos2 indicates the field's last character. If ‘.c’ is omitted from pos1, it defaults to 1 (the beginning of the field); if omitted from pos2, it defaults to 0 (the end of the field). opts are ordering options, allowing individual keys to be sorted according to different rules; see below for details. Keys can span multiple fields. 

Example: To sort on the second field, use --key=2,2 (-k 2,2). See below for more notes on keys and more examples. See also the --debug option to help determine the part of the line being used in the sort. 
于 2013-06-25T14:55:31.263 回答