I have a very simple text file of 3 fields, each is separated by a space, like following:
123 15 0 123 14 0 345 12 0 345 11 0
And I issued a sort command to sort by the first column: sort -k 1 myfile
. But it does not sort just by the first column. It sort by the whole line and I get the following result:
123 14 0 123 15 0 345 11 0 345 12 0
Is there anything wrong on my command or file?
You need to use:
if you want to sort only on the first field. This syntax specifies the start and end field for sorting.
sort -k 1
means to sort starting with the first field through to the end of the line. To ensure the lines are kept in the same order with respect to the input where the sort key is the same, you need to use a stable sort with the-s
flag (GNU).See this from the
sort(1)
man page:and the info page:
By default, sort command do sort on whole line. you should use -k option to specify which column as sorting index.