cat input.txt | sort -k1,1

I am trying to figure out what the ,1 part at the end does in this command. input.txt is a 2 column file. First column is some word and second column is the number 1. -k1 tells it to sort by the first column, so alphabetically in this case. What does the second part, ,1 do?

  • man sort and look for the -k flag... and then search further down for the KEYDEF that it refers to. – roaima Jan 25 '19 at 21:51
  • 1
    I did, but I didn't quite understand where the comma part came in when I man'ed it. – anonuser01 Jan 25 '19 at 21:54
  • Please can I suggest next time you mention that. It's good to show you've tried to solve something first, and you're less likely to get downvoted for "This question does not show any research effort." – roaima Jan 25 '19 at 21:57
  • Using GNU sort, the --debug option is nice. – Jeff Schaller Jan 25 '19 at 23:17

-k1,1 in the command

sort -k1,1 input.txt

would sort on the data using first column as the sorting key, only. The first 1 denotes the start of the sorting key as column 1, and the second 1 denotes the same column as the end of the sorting key. Had you used -k1 or -k1,2 on a file with two columns, then both columns would have been used (as would have been the case if -k was not used on the command line at all).

In short, the two digits refer to the sorting key's start and end column.

So, using -k1,1 will only use the first of your two columns as the sorting key. When two rows have the same key, however, the whole line will be used to determine the order of the two lines (unless another -k option is specified after the first, in which case that will be used before the whole line is used).

  • Sorry, I think I don't understand what you mean by the "start" and "end" of the sorting key. So say my first row is is word tall 2 So the sorting key is tall. Are the letters t and l the start and end of the sorting key respectively, if the flag -k1,1 is used? Is the letter and number t and l the start and end of the sorting key, respectively, if the flag -k1,2 is used? – anonuser01 Jan 25 '19 at 21:46
  • oh I think your update answers this question – anonuser01 Jan 25 '19 at 21:46
  • @Iamanon With -k1,1, the word tall would be used as the key to sort on. With -k1 or -k1,2, the string tall 2 would be used. With -k2 on your data, 2 would be used as the key. – Kusalananda Jan 25 '19 at 21:47
  • @Iamanon To use only the filst two characters of the first column, you would use -k1.1,1.2 I believe. – Kusalananda Jan 25 '19 at 21:49
  • Ahh. Would the sorting key be 2 tall if you used -k2,1? – anonuser01 Jan 25 '19 at 21:50

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.