bash 按列唯一排序 - 排序命令?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18354202/
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-09-18 06:19:44  来源:igfitidea点击:

Sorting unique by column - sort command?

linuxbashshellunixsorting

提问by ComputerFellow

I have this file:

我有这个文件:

hello 1
hello 2
world 1
world 2
hello 3
hi    3
hi    4

I want to sort this like so,

我想这样排序,

hello 1
hi  3
world 1

The thing is I need only the first unique item in column 1.

问题是我只需要第 1 列中的第一个唯一项目。

I tried sort -k1 -u file.txtbut it isn't working as I expect. How do I go about this?

我试过了,sort -k1 -u file.txt但它没有按我预期的那样工作。我该怎么做?

回答by potong

This might work for you:

这可能对你有用:

sort -uk1,1 file

This sorts the file on the first field only and removes duplicate lines based on the first field.

这仅在第一个字段上对文件进行排序,并根据第一个字段删除重复的行。

回答by Prakash

Sort and give unique list based on column 1

根据第 1 列排序并给出唯一列表

sort -u -t : -k 1,1 test.txt

sort -u -t : -k 1,1 test.txt

-t : = colon is separator

-t : = 冒号是分隔符

-k 1,1 = based on column 1

-k 1,1 = 基于第 1 列

Sort and give unique list based on column 1 & column 3

根据第 1 列和第 3 列排序并给出唯一列表

sort -u -t : -k 1,1 -k 3,3 test.txt

排序 -u -t : -k 1,1 -k 3,3 test.txt

-t : = colon is separator

-t : = 冒号是分隔符

-k 1,1 3,3 = based on column 1 & column 3

-k 1,1 3,3 = 基于第 1 列和第 3 列

回答by anubhava

You can pipe it to awk:

您可以将其通过管道传输到 awk:

sort -k1 file | awk '!( in a){a[]; print}'
hello 1
hi    3
world 1