using sort command

Dave Howorth dhoworth at mrc-lmb.cam.ac.uk
Mon Apr 26 15:57:20 UTC 2010


R Kimber wrote:
> I'm trying to sort a text file of the form:
> john smith, something, something
> 
> Basically, I want to sort on the surname and then on the first name, so
> that all the Smiths (e.g.) end up in order of their first name.
> 
> The man page doesn't seem to explain this. Googling suggests that
> 
> sort -k2 -k1 <filename>
> 
> ought to work, but it just seems to sort on the surname.
> 
> I'd be grateful for pointers on how to do this.
> - Richard.

I don't know where you googled but the info for sort explains it:

(from e.g. http://www.nada.kth.se/cgi-bin/info?(textutils)sort%20invocation)

     Sort numerically on the second field and resolve ties by sorting
     alphabetically on the third and fourth characters of field five.
     Use `:' as the field delimiter.

          sort -t : -k 2,2n -k 5.3,5.4

     Note that if you had written `-k 2' instead of `-k 2,2' `sort'
     would have used all characters beginning in the second field and
     extending to the end of the line as the primary *numeric* key.
     For the large majority of applications, treating keys spanning
     more than one field as numeric will not do what you expect.

You need to limit the first key to a single field.

Cheers, Dave




More information about the ubuntu-users mailing list