Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gnu sort: stray characters in field specification

sort doesn't seem to like my key specification. Why?

~/tmp $ sort --version
sort (GNU coreutils) 8.25
Packaged by Cygwin (8.25-1)
~/tmp $ echo 'a;b;c;d;e;f;g'|sort --field-separator=';' --key=1,5,2                                          
sort: stray character in field spec: invalid field specification '1,5,2'

From the man page:

-k, --key=KEYDEF : sort via a key; KEYDEF gives location and type

KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a field number and C a character position in the field; both are origin 1, and the stop position defaults to the line's end.

Since the .C and OPTS part in the KEYDEF is optional, a key specification F,F,F (i.e. just the field numbers) should be correct. What did I do wrong?

BTW, my environment is Cygwin, running the Z-shell.

like image 836
user1934428 Avatar asked Jul 06 '16 10:07

user1934428


2 Answers

The two fields in -k arg are the START AND END fields. You can specify -k ANY NUMBER OF TIMES, to sort on multiple keys. So, -k 1,1 -k 2,2 -k 3,3 will sort first on field 1, then field 2 then field 3.

like image 102
tedtoal Avatar answered Nov 05 '22 19:11

tedtoal


Oops, I should have taken the man page more literally. The definition for KEYDEF says

F[.C][OPTS][,F[.C][OPTS]]

and not

F[.C][OPTS][,F[.C][OPTS]...]

which means that only 1 or 2 fields can be supplied, not an arbitrary number. This explains the error.

As a side note, I believe there is still an error in the man page. The KEYDEF definition says that the stop position defaults to the line's end. This can't be true, can it? IMO it should be the stop position defaults to the field's end.

UPDATE: My explanation is NOT correct. See the answer provided by @tedtoal for a correct explanation.

like image 34
user1934428 Avatar answered Nov 05 '22 21:11

user1934428