"Standard answer" sort command multi-column sort/Compound condition method

Source: Internet
Author: User

This is only a small problem, but there are too many fake raiders, all send the real answer.

The data are as follows:

BA-a
ab 1 b
aa 1 c
ba 3 D

Requirements: First by first column, if repeated, and then sorted by number 2nd Column


First look at a very easy to Baidu out of the wrong answer:

Baidu Search "Sort multi-column sorting"

First: The coordinate parameter, namely sort-k1-k2n file, the output is as follows, error:

AA 1 C
ab 1 b
ba one
BA 3 d
The second one: ditto, found the problem behind, but gave the wrong explanation

Article Three: The answer is yes, but not explained, sort-k1,1-k2,2n file, the output is as follows:

AA 1 C
ab 1 b
ba 3 d
ba One


And then face the wrong all have. So please remember to have a long memory, here omitted ...


Positive Solutions and reasons:

The answer is: sort-k1,1-k2,2n file

The reason is simple, as long as the man sort a look at the instructions on the line:

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. If neither-t Nor-b is in effect, characters in a field are counted the beginning of the preceding
whitespace.  OPTS is one or more single-letter ordering options [BDFGIMHNRRV], which override global ordering the options for that key. If no key is given, use
The entire line as the key.
It's clear, K's argument is a pair, start and end, if not specified end, the default is the line end, not the end of the field. The reason for the other person's error is that if the field is equal in length and the test fields are adjacent, no numbers are specified, which can cause some coincidences.


Again,-K2 is not sorted by the 2nd column, but the 2nd column begins, and all content is sorted at the end of the line.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.