在 Linux 中按第三列排序,第一列和第二列保持不变?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11006431/
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
Sort by third column leaving first and second column intact in Linux?
提问by user1429246
I need to sort a flat file by third column leaving first column intact [First column is already sorted] (in linux). (second column may change)
我需要按第三列对平面文件进行排序,使第一列保持不变[第一列已经排序](在 linux 中)。(第二列可能会改变)
Example i/p file:-
示例 i/p 文件:-
b:di:wave
b:di12:red
b:di12:wave
b:di06:pir
Should look like:-
应该看起来像:-
b:di06:pir
b:di12:red
b:di12:wave
bast:di:wave
I tried several sorting options but I could sort only by second column but not third.
我尝试了几种排序选项,但我只能按第二列排序,而不能按第三列排序。
Can someone please help ?
有人可以帮忙吗?
采纳答案by Levon
Try this:
尝试这个:
sort -t: -k1,1 -k3 data.txt
gives:
给出:
bast:disp-san-d5-06:piranha
bast:display-san-12:redbird
bast:display-san-07:waverider
bast:display-san-12:waverider
This will sort with the 1st field as primary key, and the 3rd field as secondary key splitting the line into fields by :
这将使用第一个字段作为主键进行排序,将第三个字段作为辅助键将行拆分为多个字段 :
Details:
详情:
data.txt
contains the 4 lines from your post.
data.txt
包含您帖子中的 4 行。
You can specify multiple fields as sorting keys, see the man page
您可以指定多个字段作为排序键,请参阅手册页
-k1,1
means sort on the first field(start at field 1 and end at field 1, otherwise it would continue using the rest of the line for determining the sort)
-k1,1
表示在第一个字段上排序(从字段 1 开始并在字段 1 结束,否则它将继续使用该行的其余部分来确定排序)
-k3
means sort on the 3rd fieldas secondary key. Since there are no other fields behind it is not necessary to specify -k3,3
but it wouldn't hurt either.
-k3
表示在第三个字段上排序作为辅助键。由于后面没有其他字段,因此无需指定,-k3,3
但也不会受到伤害。
-t:
means delimit fields in lines with the :
character, otherwise blank is used by default
-t:
表示用:
字符分隔行中的字段,否则默认使用空白
More information see this SO question Sorting multiple keys with Unix sortand the sort man page
更多信息请参见这个 SO 问题Sorting multiple keys with Unix sort和sort 手册页