Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse sort order of a multicolumn file in BASH

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 gives me the inversed order.

The results should be:

1 6 7 1 4 5 2 3 5 5 2 1 1 2 3 
like image 721
Valerio D. Ciotti Avatar asked Jan 02 '13 10:01

Valerio D. Ciotti


People also ask

How do I sort in reverse order in bash?

How to sort in reverse order. To sort in reverse order pass the -r option to sort . This will sort in reverse order and write the result to standard output.

How do I sort files in reverse order?

2. -r Option: Sorting In Reverse Order: You can perform a reverse-order sort using the -r flag. the -r flag is an option of the sort command which sorts the input file in reverse order i.e. descending order by default. Example: The input file is the same as mentioned above.

How do I reverse a list order in Linux?

To reverse the listing of files by name, add the -r (reverse) option. This will be like turning the normal listing upside down.

How do you sort in ascending order in bash?

Sort a File Numerically To sort a file containing numeric data, use the -n flag with the command. By default, sort will arrange the data in ascending order. If you want to sort in descending order, reverse the arrangement using the -r option along with the -n flag in the command.


1 Answers

sort -nrk 2,2 

does the trick.

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

like image 51
Danstahr Avatar answered Oct 05 '22 15:10

Danstahr