Sorting based on the second field

Oracle Enterprise Linux 6

This is my file. Two fields separated by space

$ cat testfile.txt
MARCH9 MARCH4
MARCH1 MARCH5
MARCH2 MARCH326
MARCH821 MARCH7
MARCH6 MARCH2
$
$

The following numeric sort, based on the first field's 6th character works as expected.

$
$ sort -n -k  1.6 testfile.txt
MARCH1 MARCH5
MARCH2 MARCH326
MARCH6 MARCH2
MARCH9 MARCH4
MARCH821 MARCH7
$

But the following attempt to sort the lines based on the second field's numeric character doesn't seem to work.
--- In the below example for "-k 2.6" , 2 denotes second field, 6 denotes the character based on which sort should happen (I have a numeric sort here)

$
$ sort -n -k  2.6 testfile.txt
MARCH1 MARCH5
MARCH2 MARCH326
MARCH6 MARCH2
MARCH821 MARCH7
MARCH9 MARCH4
# sort -k2 testfile
MARCH6 MARCH2
MARCH2 MARCH326
MARCH9 MARCH4
MARCH1 MARCH5
MARCH821 MARCH7

cheers,
Devaraj Takhellambam

Mention the delimiter

$ sort -t" " -n -k  2.6 file
MARCH6 MARCH2
MARCH9 MARCH4
MARCH1 MARCH5
MARCH821 MARCH7
MARCH2 MARCH326
1 Like

Try

$ sort -n -k2.7 file

Reason:

man sort :

1 Like

Thanks Anbu. You solution worked.
Thank you Rudic . You solution worked as well.

 
$ sort -n -k 2.7 myfile.txt
MARCH6 MARCH2
MARCH9 MARCH4
MARCH1 MARCH5
MARCH821 MARCH7
MARCH2 MARCH326

But what is 7 ? It should be sorting from 6th character onwards. Right ?

Did you read the quote from sort's man page?

1 Like

Got it. Its because of this . Right ?

 
If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace

Right!