unexpected behavior of unix sort

53 Views Asked by At

Hi I am trying to use unix sort function. I wanted to sort the file by 3rd column

Here are the content of the file

tcsh 541% cat file
2,2587,769,629,629,629,890,890,890,890,89,801,0,184,24944,8018,42839
1,2622,867,686,686,686,880,880,880,880,88,792,0,246,25551,7977,43721
3,2636,736,700,700,700,1083,880,880,880,88,792,0,260,25439,7984,43758

When i try to sort it by column 1 it works

tcsh 533% sort -t, -nk1 file
1,2622,867,686,686,686,880,880,880,880,88,792,0,246,25551,7977,43721
2,2587,769,629,629,629,890,890,890,890,89,801,0,184,24944,8018,42839
3,2636,736,700,700,700,1083,880,880,880,88,792,0,260,25439,7984,43758

When i try to sort it by column 2 it works.

tcsh 534% sort -t, -nk1 file | sort -t, -nk2
2,2587,769,629,629,629,890,890,890,890,89,801,0,184,24944,8018,42839
1,2622,867,686,686,686,880,880,880,880,88,792,0,246,25551,7977,43721
3,2636,736,700,700,700,1083,880,880,880,88,792,0,260,25439,7984,43758

But when i try to sort it by column 3 it doesnt work

tcsh 535% sort -t, -nk1 file | sort -t, -nk3
2,2587,769,629,629,629,890,890,890,890,89,801,0,184,24944,8018,42839
1,2622,867,686,686,686,880,880,880,880,88,792,0,246,25551,7977,43721
3,2636,736,700,700,700,1083,880,880,880,88,792,0,260,25439,7984,43758

tcsh 532% sort -t, -nk3 file
2,2587,769,629,629,629,890,890,890,890,89,801,0,184,24944,8018,42839
1,2622,867,686,686,686,880,880,880,880,88,792,0,246,25551,7977,43721
3,2636,736,700,700,700,1083,880,880,880,88,792,0,260,25439,7984,43758

The expected output is (updated based on Knitt's comment)

tcsh 532% sort -t, -nk3 file
3,2636,736,700,700,700,1083,880,880,880,88,792,0,260,25439,7984,43758
2,2587,769,629,629,629,890,890,890,890,89,801,0,184,24944,8018,42839
1,2622,867,686,686,686,880,880,880,880,88,792,0,246,25551,7977,43721

SORT version :

542% sort --version sort (GNU coreutils) 8.22 Copyright (C) 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Written by Mike Haertel and Paul Eggert

2

There are 2 best solutions below

0
arun On BEST ANSWER

As @knittl suggested after below settings

setenv LC_ALL C

Getting expected output

tcsh 545% sort -t, -nk3 file
3,2636,736,700,700,700,1083,880,880,880,88,792,0,260,25439,7984,43758
2,2587,769,629,629,629,890,890,890,890,89,801,0,184,24944,8018,42839
1,2622,867,686,686,686,880,880,880,880,88,792,0,246,25551,7977,43721

Got more information about LC_ALL here

0
Philippe On

Following specification of the option -k fixes the problem :

sort -t, -nk3,3 file