bash 从最长到最短的排序线
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8296649/
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
Sorting lines from longest to shortest
提问by Village
How can I rearrange all of the lines in a file from longest to shortest? For e.g.:
如何从最长到最短重新排列文件中的所有行?例如:
elephant
zoo
penguin
Would be changed to
将改为
elephant
penguin
zoo
回答by thiton
Add the line length as the first field of the line, sort, and remove the line length:
添加行长作为行的第一个字段,排序并删除行长:
awk '{ print length(perl -ne '@a = <>; print sort { length $b <=> length $a } @a' file
) " " {
c = length
m[c] = m[c] ? m[c] RS ##代码## : ##代码##
} END {
for (c in m) q[++x] = m[c]
while (x) print q[x--]
}
; }' $file | sort -r -n | cut -d ' ' -f 2-
回答by lzc
TIM (my terse version for TIMTOWTDI... hmm but now it's long already :(
TIM(我的 TIMTOWTDI 简洁版本......嗯,但现在已经很久了:(
##代码##lets reserve reverse
and push
when needed
让我们保留reverse
并push
在需要时
and I wonder how long it would take on that 550MB file
我想知道这个 550MB 的文件需要多长时间
回答by Chris Koknat
Perl version, with a tip of the hat to @thiton:
Perl 版本,向@thiton 致敬:
perl -ne 'print length($_)." $_"' file | sort -r -n | cut -d ' ' -f 2-
perl -ne 'print length($_)." $_"' file | sort -r -n | cut -d ' ' -f 2-
$_
is the current line, similar to awk's $0
$_
是当前行,类似于 awk 的 $0
perl-5.24 execution on a 550MB .txt file with 6 million lines (British National Corpus) took 24 seconds
perl-5.24 在 600 万行(英国国家语料库)的 550MB .txt 文件上执行需要 24 秒
@thiton's awk (3.1.7) execution took 26 seconds
@thiton 的 awk (3.1.7) 执行耗时 26 秒
With a tip of the hat to @William Pursell from a related post:
从相关帖子中向@William Pursell 致敬:
perl -ne 'push @a, $_; END{ print reverse sort { length $a <=> length $b } @a }' file
perl -ne 'push @a, $_; END{ print reverse sort { length $a <=> length $b } @a }' file
perl-5.24 execution took 12.0 seconds
perl-5.24 执行耗时 12.0 秒