It sounds like you will need to make extensive use
of the "sort" command. Take a look at...
http://unix.about.com/library/weekly/aa021201a.htm
...Once you have absorbed that info. try out some things.
If/When you get stuck, post some details like...
Version of UNIX (AIX, Linux, HP, etc)
Version of Shell (sh, ksh, csh, bash)
...as well as code fragments and any error messages
you may get attempting to execute it.
You may also want to check the FAQ's on this
forum for books and sites on shell programming.