Sorting a file by multiple columns

From Docswiki
Revision as of 12:40, 13 May 2019 by Adk44 (talk | contribs) (Created page with "If you have a file you want to sort using multiple columns of numbers, the ''sort'' command is your new best friend! For example, here is a section from a file I'm trying to...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

If you have a file you want to sort using multiple columns of numbers, the sort command is your new best friend!

For example, here is a section from a file I'm trying to sort. I'd like to sort it first by the first column and then sort it by the third column, ignoring the second column.

4       1       3
0       2       0
3       3       4
4       4       3
3       5       3
3       6       3
3       7       3
4       8       4
3       9       4
3       10      3

We can achieve this using the following command:

sort -k 1,1n -k 3,3n metric > metric.ordered

The -k option specifies a column, 1,1 means start at the top of the first column, and sort till the end of the first column. The n indicates it should do a 'numerical sort'. You can specify as many of these -k options as you like, making sort a very powerful tool! :) Here is the result:

0       2       0
3       10      3
3       5       3
3       6       3
3       7       3
3       3       4
3       9       4
4       1       3
4       4       3
4       8       4

You can find more about sort in this handy blog post.