unix 命令:如何获取前 n 条记录 [英] unix command: how to get top n records
本文介绍了unix 命令:如何获取前 n 条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 unix 命令获取前 n 条记录:
I want to get top n records using unix command:
例如输入:
- 1个
- 2 b
- 3 c
- 4 天
- 5 e
输出(获得前 3 个):
output(get top 3):
- 5 e
- 4 天
- 3 c
目前我在做什么:
cat myfile.txt | sort -k1nr | head -3 > my_output.txt
它工作正常,但当文件变大时,它变得很慢.
It works fine but when the file gets large, it becomes very slow.
它很慢,因为它对文件进行了完全排序,而我需要的只是前 3 条记录.
It is slow because it sorts the file completely, while what I need is just the top 3 records.
有什么命令可以用来获取前 3 条记录吗?
Is there any command I can use to get the top 3 records?
推荐答案
perl -ane '
BEGIN {@top = ([-1]) x 3}
if ($F[0] > $top[0][0]) {
@top = sort {$a->[0] <=> $b->[0]} @top[1,2], [$F[0], $_];
}
END {print for reverse map {$_->[1]} @top}
' << END_DATA
1 a
2 b
3 c
4 d
5 e
END_DATA
5 e
4 d
3 c
这篇关于unix 命令:如何获取前 n 条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文