如何将文件中的行从最短到最长排序?

Vil*_*age 2 sorting bash awk

从最长到最短的排序行类似,如何将文件中的所有行从最短到最长排序?例如"

This is a long sentence.
This is not so long.
This is not long.

那就变成:

This is not long.
This is not so long.
This is a long sentence.

Mat*_*ler 5

它几乎与你给出的链接完全相同

awk '{ print length($0) " " $0; }' $file | sort -n | cut -d ' ' -f 2-
Run Code Online (Sandbox Code Playgroud)

-r选项是扭转排序.


Wil*_*ell 5

perl -ne 'push @a, $_ } { print sort { length $a <=> length $b } @a' input
Run Code Online (Sandbox Code Playgroud)

(在我的盒子上,这比awk | sort | cut解决方案快了大约4倍.)

请注意,这使用了一种可怕的perl习惯用法并且滥用语义-n来节省一些击键.把它写成最好是:

perl -ne '{ push @a, $_ } END { print sort { length $a <=> length $b } @a }' input
Run Code Online (Sandbox Code Playgroud)