与Sorting lines from longest to shortest类似,如何将文件中的所有行从最短到最长排序? E.g“。
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.
答案 0 :(得分:5)
它几乎与您提供的链接完全相同
awk '{ print length($0) " " $0; }' $file | sort -n | cut -d ' ' -f 2-
-r
选项用于反转排序。
答案 1 :(得分:5)
perl -ne 'push @a, $_ } { print sort { length $a <=> length $b } @a' input
(在我的方框中,这比awk | sort | cut
解决方案快4倍。)
请注意,这会使用可怕的perl习惯用法并滥用-n
的语义来节省一些键击。最好把它写成:
perl -ne '{ push @a, $_ } END { print sort { length $a <=> length $b } @a }' input
答案 2 :(得分:1)
答案 3 :(得分:0)
请注意,此解决方案在大输入时效果不佳。
您也可以在awk
中进行排序:
cat << EOF > file
This is a long sentence.
This is not so long.
This is not long.
EOF
sort.awk
# Only find length once
{ len = length($0) }
# If we haven't seen this line before add it to the lines array
# and move on to next record
lines[len] == "" { lines[len] = $0; next }
# A duplicate, append to the previous record
{ lines[len] = lines[len] RS $0 }
END {
# lines array is sorted according to the indices, the sorted
# indices are stored in the indices array
asorti(lines, indices)
for(key in indices)
print lines[indices[key]]
}
像这样跑:
awk -f sort.awk file
或者作为一个单行:
< file awk '{ len = length($0) } lines[len] == "" { lines[len] = $0; next } { lines[len] = lines[len] RS $0 } END { asorti(lines, indices); for(key in indices) print lines[indices[key]] }'
输出:
This is not long.
This is not so long.
This is a long sentence.
答案 4 :(得分:0)
另一个perl实现:
perl -ne 'print length($_)." $_"' file | sort -n | cut -d ' ' -f 2-
$_
是当前行,类似于awk&#39; s $0