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-
$ awk '{print length"\t"$0}' File | sort -rn | cut -f2-
which is basically the same thing except that cut operates on tabs per default so ignore this :-) –
Multilingual $ awk '{print length"\t"$0}' tlds-alpha-by-domain.txt
outputs ` "$0}' tlds-alpha-by-domain.txt2 AC`etc... Using the longer version without tabs generates safer terminal/command output. At least when running in bash version 3.2 on Mac OS X 10.7.5. –
Homily cat
, like this: < input_file command1 | command2 | commmand3 > output_file
–
Articulation build.gradle
by using: find $PWD -name "build.gradle" | awk '{print length($0), $0 | "sort -n"}' | head -1 | cut -d ' ' -f 2-
–
Paunch 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
With POSIX Awk:
{
c = length
m[c] = m[c] ? m[c] RS $0 : $0
} END {
for (c in m) q[++x] = m[c]
while (x) print q[x--]
}
© 2022 - 2024 — McMap. All rights reserved.
pip search json |awk '{print length($1)"\t"$1}' |sort -rn |cut -d' ' -f2-
. Obviously "pip search json" is just there to produce output instead of a filename. – Impaction