2

Using GNU sort. I want to print only the first of a group of lines, based on duplicate key(s).

-k1,2 works as expected – only the 1st sorted line is output

printf %s\\n 'a a c' 'a a b' 'a a a' | sort -u -k1,2 -t' '
# a a a

-k1 does not work as expected – all 3 sorted lines are output

printf %s\\n 'a a c' 'a a b' 'a a a' | sort -u -k1 -t' '
# a a a
# a a b
# a a c

Is this normal for all variants of sort, or is it just GNU sort? It seems rather prone to 'unexpected results', as man sort shows the 2nd key number as optional: -k, --key=POS1[,POS2]

-k1,1 does work with -u, wheras a plain sort (ie. no -u) works with just -k1.

  • I'm using sort (GNU coreutils) 8.21 and the manual says, when describing KEYDEF "... and the stop position defaults to the line's end", which appears to be what you are getting. – X Tian May 28 '15 at 15:21
3

I think this is POSIX default behavior as stated in man page:

-k field_start[type][,field_end[type]]

shall define a key field that begins at field_start and ends at field_end inclusive, unless field_start falls beyond the end of the line or after field_end, in which case the key field is empty. A missing field_end shall mean the last character of the line.

  • 1
    This is the POSIX standard behaviour. – cjm May 28 '15 at 15:24
  • @cjm, I added this to answer. – taliezin May 28 '15 at 15:28
  • Thanks. If only I had read the next line after my quoted "-k, --key=POS1[,POS2]" manpage reference. It states, "start a key at POS1 (origin 1), end it at POS2 (default end of line)" - durr! :) – Peter.O May 28 '15 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.