lensort: Sort Lines by Length

A nice little script to sort lines from shortest to longest can be handy when you're writing and want to find your big words:

deroff uniq 
% deroff -w report | uniq -d | lensort a an ... deoxyribonucleic

Once I used it to sort a list of pathnames:

find 
% find adir -type f -print | lensort adir/.x adir/.temp ... adir/subdir/part1/somefile adir/subdir/part1/a_test_case

The script uses awk () to print each line's length, followed by the original line. Next, sort sorts the lengths numerically (). Then sed () strips off the lengths and the spaces - and prints the lines:

#! /bin/sh awk 'BEGIN {
 FS=RS
}
{
 print length, $0 }' $* | # Sort the lines numerically sort +0n -1 | # Remove the length and the space and print each line sed 's/^[0-9][0-9]* //'

(Some awks require a semicolon after the first curly bracket - that is, { FS=RS }; .)

- JP