sorting - How to Sort in Unix using a specific location

06
2014-04
  • sked

    Hi I have a large text file that I want to sort using a specific location (e.g. 6-12 characters)

    Ex. Input:

    12345222 ABC DEG123456 AAA BBB
    12345111VABCGDEG123456 AAA BBB
    12345111AABCGDEG123456HAAAJBBB
    

    Output (using the 6-12characters as the sort key):

    12345111AABCGDEG123456HAAAJBBB
    12345111VABCGDEG123456 AAA BBB
    12345222 ABC DEG123456 AAA BBB
    

    Note: some of the values in the sort key may or may have values.

  • Answers
  • John1024
    $ sort -t$'\n' -k1.6,1.12 file_to_be_sorted
    12345111AABCGDEG123456HAAAJBBB
    12345111VABCGDEG123456 AAA BBB
    12345222 ABC DEG123456 AAA BBB
    

  • Related Question

    sorting - How to UNIX sort by one column only?
  • ssn

    I know that the -k option for the Unix sort allow us to sort by a specific column and all of the following. For instance, given the input file:

    2 3
    2 2
    1 2
    2 1
    1 1
    

    Using sort -n -k 1, I get an output sorted by the 1st column and then by the 2nd:

    1 1
    1 2
    2 1
    2 2
    2 3
    

    However, I want to keep the 2nd column ordering, like this:

    1 2
    1 1
    2 3
    2 2
    2 1
    

    Is this possible with the sort command?


  • Related Answers
  • Jefromi

    Give this a try:

    sort -s -n -k 1,1
    

    The -s disables 'last-resort' sorting, which sorts on everything that wasn't part of a specified key.

    The -k 1 doesn't actually mean "this field and all of the following" in the context of numeric sort, as you can see if you try to sort on the second column. You're merely seeing ties broken by going to the rest of the line. In general, however, you need to specify -k 1,1 to sort only on field one.

  • tidbeck

    To only sort on the first column you should do:

    sort -n -k1,1
    

    From Unix and Linux System Administration Handbook

    sort accepts the key specification -k3 (rather than -k3,3), but it probably doesn’t do what you expect. Without the terminating field number, the sort key continues to the end of the line