The Sort command does not work as expected

2019-07-15 09:07发布

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?

标签: shell
2条回答
狗以群分
2楼-- · 2019-07-15 09:23

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.
查看更多
Rolldiameter
3楼-- · 2019-07-15 09:35

By default, sort command do sort on whole line. you should use -k option to specify which column as sorting index.

查看更多
登录 后发表回答