[Chapter 36] 36.9 Sorting a List of People by Last Name
Author: Jerry Peek, Tim O'Reilly & Mike Loukides
Date: 1998-08-04T21:48:47Z

#

| Chapter 36 Sorting |

## 36.9 Sorting a List of People by Last Name

It's hard to sort any old list of peoples' names because some people have one-word first and last names like Joe Smith, but other people have multi-part names like Mary Jo Appleton. This program sorts on the last word in each name. That won't take care of the way that names are used everywhere in the world, but it might give you some ideas...

The script reads from files or its standard input; it writes to standard output.

>     #! /bin/sh
>     # Print last field (last name), a TAB, then whole name:
>     awk '{print $NF "\t" $0}' $* |
>     # sort (by last name: the temporary first field)
>     sort |
>     # strip off first field and print the names:
>     cut -f2-

Article 16.21 uses a similar trick to find directories that have the same name.

- JP

36.8 lensort: Sort Lines by Length |  | 37. Perl, a Pathologically Eclectic Rubbish Lister