start page | rating of books | rating of authors | reviews | copyrights

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 36.7 Sorting Multiline Entries Chapter 36
Sorting
Next: 36.9 Sorting a List of People by Last Name
 

36.8 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 ( 33.11 ) to print each line's length, followed by the original line. Next, sort sorts the lengths numerically ( 36.5 ) . Then sed ( 34.24 ) 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 awk s require a semicolon after the first curly bracket - that is, { FS=RS }; .)

- JP


Previous: 36.7 Sorting Multiline Entries UNIX Power Tools Next: 36.9 Sorting a List of People by Last Name
36.7 Sorting Multiline Entries Book Index 36.9 Sorting a List of People by Last Name

The UNIX CD Bookshelf Navigation The UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System