4

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?

5
  • But it is still sorted by the first column. What's ur expected output? Commented Dec 13, 2012 at 20:26
  • It also sorts the second column, which I do not want. Actually it sorts the whole line, even I specified -k1 Commented Dec 13, 2012 at 20:38
  • The data in your file is already sorted by the first column. Commented Dec 13, 2012 at 20:41
  • I just put the first few lines of my data. The problem is that it does not only sort by the first column, but the whole line. Commented Dec 13, 2012 at 20:44
  • @Annjawn The expected output is the same as the input Commented Dec 4, 2019 at 19:10

1 Answer 1

6

You need to use:

sort -k 1,1 -s myfile

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:

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.

and the info page:

The --stable (-s) option disables this last-resort comparison so that
lines in which all fields compare equal are left in their original relative
order.
Sign up to request clarification or add additional context in comments.

3 Comments

Still sorts the second column though!
well in my system it says sort: Not a recognized flag: s. its a unix environment.
@Annjawn: Then it looks like your sort does not do a stable sort with -s. You'll need to install gnu, or find another option that your sort has. BTW "a unix environment" is a very vague description of your system.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.