Advertisement

Why doesn't sort work like it's documented to?

Started by February 27, 2002 11:18 AM
2 comments, last by Russell 22 years, 7 months ago
I tried to sort the following file using the sort command, and it''s not working right. Mary K. O''Henry 138037 13 John S. Daniel 135819 5 John M. Daniel 135820 5 Abe Z. Daniel 138925 2 Jim B. Oak 138011 7 The file is called names. I wanted to sort the file like you would a phone book, so I added the -d option for a dictionary sort to remedy the apostrophe in O''Henry, the -f option to make Oak come before O''Henry, and then I wanted to sort accordin to last name, first name, middle initial. So I tried the following command. sort -df -k3 -k1 -k2 names That doesn''t even sort the Daniels according to their first names, much less the middle initials. I messed around with the -b option to remove the leading space to try to fix the middle initial problem, because there are two spaces between John and his middle initial S. I''m stumped. Any thoughts? Russell
I figured it out..

sort -df -k 3,3 -k 1,1 -k 2b,2 names
Advertisement
Yeah.

-k doesn''t really work backwards and is only used once if I''m right. What you should do it reformat the fields, sort, and kick out the right output. Use awk

cat test | awk ''{print $3" "$1" "$2" "$4" "$5}'' | sort -df -k1,3 | awk ''{print $1" "$2" "$3" "$4" "$5}''

There is probably a way to force awk to format each column automatically with a space and I would probably turn this into a little shell script if will be using it on more robust files. You might also want to use Perl instead if it''s going to be for larger formats.

Here, you will display the contents, pipe them into awk which will reformat them as "Last Name, First Name, Middle Init, UID, Num". Then the pipe that result to sort, which will do a dictionary, case insensitive sort on the new format (which is Last, First, Middle as you want), then to put this format back in it''s origional form, awk is called again this time back in the origional column order.

Hope that helps

Reuben

Rube
Nice. This is why I love Unix, years later still learning new twists.

Thanks for the update.

Rube

This topic is closed to new replies.

Advertisement