Linux Bash 输出具有最高值的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13581225/
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
Bash output the line with highest value
提问by teutara
my question is pretty much like this onebut with one difference; i want the output the line that has highest score on the 3rd tab. my data is like:
我的问题很像这个,但有一点不同;我希望输出在第三个选项卡上得分最高的行。我的数据是这样的:
1.gui Qxx 16
2.gui Qxy 23
3.guT QWS 11
and i want to get this:
我想得到这个:
1.gui Qxy 23
3.guT QWS 11
I used:
我用了:
cat file.f | uniq | cut -d" " -f3 | sort | uniq -d >>out.f
but did not get what i want!?
但没有得到我想要的!?
采纳答案by Chris Seymour
With sort
:
与sort
:
$ sort -rk3 file # Sort on column 3, display all results
2.gui Qxy 23
1.gui Qxx 16
3.guT QWS 11
$ sort -rk3 file | head -2 # Sort on column 3, filter number of results
2.gui Qxy 23
1.gui Qxx 16
$ sort -rk3 file | uniq # Sort on column 3, on display unique results
2.gui Qxy 23
1.gui Qxx 16
3.guT QWS 11
-r
reverse sort, highest first.
-r
反向排序,最高的在前。
-k3
sort on the 3rd column.
-k3
对第 3 列进行排序。
If you only want to display line which the 3rd column is greater than some value (i.e. 15)then try this using awk
:
如果您只想显示第 3 列大于某个值(即 15)的行,请尝试使用awk
:
awk '>15' file | sort -rk3 # Display line where column 3 > 15 and sort
2.gui ?Qxy ?23
1.gui ?Qxx ?16
回答by teutara
for future users with same question:
对于有相同问题的未来用户:
do not forget to introduce -n switch to the -sort
command, or your values are ordered starting from 9999's and followed by 999's etc.. so use
不要忘记在-sort
命令中引入 -n 开关,或者您的值从 9999 开始排序,然后是 999 等。所以使用
sort -rnk3 file
and if you want to get only one line with highest value (remove duplicates) use this:
如果您只想获得具有最高值的一行(删除重复项),请使用以下命令:
sort -rnk3 file | awk '!x[]++'
and if you have an usual delimiter you can tell -awk
to notice:
如果你有一个常用的分隔符,你可以告诉-awk
注意:
sort -rnk3 file | awk -F"[. ]" '!x[]++'
回答by Eric González
This must give you the highest value for those lines where the name is repeated and conserve those lines that have not repeated names.
这必须为那些名称重复的行提供最高值,并保留那些没有重复名称的行。
sort -rk3 file | awk '!seen[]++' > file_filtered.txt