Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple field and numeric sort

Tags:

bash

sorting

List of files:

sysbench-size-256M-mode-rndrd-threads-1
sysbench-size-256M-mode-rndrd-threads-16
sysbench-size-256M-mode-rndrd-threads-4
sysbench-size-256M-mode-rndrd-threads-8
sysbench-size-256M-mode-rndrw-threads-1
sysbench-size-256M-mode-rndrw-threads-16
sysbench-size-256M-mode-rndrw-threads-4
sysbench-size-256M-mode-rndrw-threads-8
sysbench-size-256M-mode-rndwr-threads-1
sysbench-size-256M-mode-rndwr-threads-16
sysbench-size-256M-mode-rndwr-threads-4
sysbench-size-256M-mode-rndwr-threads-8
sysbench-size-256M-mode-seqrd-threads-1
sysbench-size-256M-mode-seqrd-threads-16
sysbench-size-256M-mode-seqrd-threads-4
sysbench-size-256M-mode-seqrd-threads-8
sysbench-size-256M-mode-seqwr-threads-1
sysbench-size-256M-mode-seqwr-threads-16
sysbench-size-256M-mode-seqwr-threads-4
sysbench-size-256M-mode-seqwr-threads-8

I would like to sort them by mode (rndrd, rndwr etc.) and then number:

sysbench-size-256M-mode-rndrd-threads-1
sysbench-size-256M-mode-rndrd-threads-4
sysbench-size-256M-mode-rndrd-threads-8
sysbench-size-256M-mode-rndrd-threads-16
sysbench-size-256M-mode-rndrw-threads-1
sysbench-size-256M-mode-rndrw-threads-4
sysbench-size-256M-mode-rndrw-threads-8
sysbench-size-256M-mode-rndrw-threads-16
....

I've tried the following loop but it's sorting by number but I need sequence like 1,4,8,16:

$ for f in $(ls -1A); do echo $f; done | sort -t '-' -k 7n

EDIT:

Please note that numeric sort (-n) sort it by number (1,1,1,1,4,4,4,4...) but I need sequence like 1,4,8,16,1,4,8,16...

like image 326
HTF Avatar asked Jan 13 '23 12:01

HTF


2 Answers

Sort by more columns:

sort -t- -k5,5 -k7n

Primary sort is by 5th column (and not the rest, that's why 5,5), secondary sorting by number in the 7th column.

like image 100
choroba Avatar answered Jan 18 '23 10:01

choroba


The for loop is completely unnecessary as is the -1 argument to ls when piping its output. This yields

ls -A | sort -t- -k 5,5 -k 7,7n

where the first key begins and ends at column 5 and the second key begins and ends at column 7 and is numeric.

like image 26
msw Avatar answered Jan 18 '23 10:01

msw