sorting pathnames by basename

Michael O'Donnell mod+gnhlug at std.com
Mon Aug 19 15:46:40 EDT 2002


Given a list of pathnames, I'd like to be able to
sort that list by the basename of each file in the
list, ie.  the pathname

   q/r/s/t/u/v/aaa

...would sort ahead of

   aaaa/aaaa/bbb

...because the basename 'aaa' sorts lexicographically
ahead of 'bbb'.

My current approach is a bit clunky but works as long as
the pathnames in question contain no spaces, thus:

   sed -e 's;/\([^/]*\)$; \1;' | sort -bfd +1 | sed -e 's; ;/;'

...which replaces the last slash in each pathname with
a space, sorts that list of dual-field space-delimited
records keyed on the second field, and then replaces
the slashes.  Suggestions for improvement welcome.




More information about the gnhlug-discuss mailing list