# How to sort the values in one column based on other column values?

I want to sort the given tab separated data.

• first level is column #1 and is sorted in increasing order
• second level is column #2 is also sorted in increasing order, (but conditional); condition: column #3 should be grouped by unique values but sort order in column #2, should also be preserved as much as possible (with smallest range being at top).
• column #3 isn't sorted at all, but should be grouped.

Input Data:

``````2    15881764  9         C|T
2    15881767  9         C|C
2    15881989  4         C|C
2    15882091  4         G|T
2    15882451  9         C|T
2    15882454  9         C|T
2    15882493  9         C|T
2    15882505  6         A|T
3    16882450  6         C|T
3    16882594  6         C|T
3    16882633  6         C|T
3    16882755  6         A|T
``````

Expected output:

``````2    15881764  9         C|T
2    15881767  9         C|C
2    15882451  9         C|T
2    15882454  9         C|T
2    15882493  9         C|T
2    15881989  4         C|C
2    15882091  4         G|T
2    15882505  6         A|T
3    16882450  6         C|T
3    16882594  6         C|T
3    16882633  6         C|T
3    16882755  6         A|T
``````

Any unix based utilities is fine, but sort and awk preferable, owing to readability.

• If you're happy with one or several of the answers, upvote them. If one is solving your issue, accepting it would be the best way of saying "Thank You!" Accepting an answer also indicates to future readers that the answer actually solved the problem. – Kusalananda Feb 17 '18 at 8:32

``````sort -k1,1n -k3,3n -k2,2n file
``````

Sort first by col 1 numerically.
If there is a tie, then by col 3 numerically.
If there is a tie, then by col 2 numerically.

• I had explained my way of data sorting, but looks like the wording or the input wasn't enough to say what I intended. – everestial007 Feb 17 '18 at 1:40
• The question has changed a little bit. Can you have a look at it? – everestial007 Feb 17 '18 at 18:24

I think your problem is solved if you do a `sort` on the third field, just `sort -n -k3` but for the best you could do

``````sort -t\$'\t' -n -k3 -k2 -k1 file
``````

If you look at the `man` page of `sort` you would see the `-k` denotes the field in the each line default delimited by space that you want to sort on. The `-t` flag allows you to set the de-limiter which according to your last edit being a Tab character.

• a brief explanation please. Why k3 first? – everestial007 Feb 13 '18 at 17:37
• Because you specify that all entries should be grouped by that field? – DopeGhoti Feb 13 '18 at 17:38
• @everestial007: Hope my last edit was useful – Inian Feb 13 '18 at 17:42