Friday, October 28, 2022

[SOLVED] Reverse sort order of a multicolumn file in BASH

Issue

I've the following file:

1 2 3
1 4 5
1 6 7
2 3 5
5 2 1

and I want that the file be sorted for the second column but from the largest number (in this case 6) to the smallest. I've tried with

sort +1 -2 file.dat

but it sorts in ascending order (rather than descending).

The results should be:

1 6 7
1 4 5
2 3 5
5 2 1
1 2 3

Solution

sort -nrk 2,2

does the trick.

n for numeric sorting, r for reverse order and k 2,2 for the second column.



Answered By - Danstahr
Answer Checked By - David Marino (WPSolving Volunteer)