The Sort command does not work as expected

后端 未结 1 641
孤街浪徒
孤街浪徒 2020-12-04 02:38

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 comma

相关标签:
1条回答
  • 2020-12-04 02:54

    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.
    
    0 讨论(0)
提交回复
热议问题