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
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
Add the line length as the first field of the line, sort, and remove the line length:
awk '{ print length($0) " " $0; }' $file | sort -r -n | cut -d ' ' -f 2-
TIM (my terse version for TIMTOWTDI... hmm but now it's long already :(
perl -ne '@a = <>; print sort { length $b <=> length $a } @a' file
lets reserve reverse
and push
when needed
and I wonder how long it would take on that 550MB file
Perl version, with a tip of the hat to @thiton:
perl -ne 'print length($_)." $_"' file | sort -r -n | cut -d ' ' -f 2-
$_
is the current line, similar to awk's $0
perl-5.24 execution on a 550MB .txt file with 6 million lines (British National Corpus) took 24 seconds
@thiton's awk (3.1.7) execution took 26 seconds
With a tip of the hat to @William Pursell from a related post:
perl -ne 'push @a, $_; END{ print reverse sort { length $a <=> length $b } @a }' file
perl-5.24 execution took 12.0 seconds