Alternate to sort --random-sort

sort --random-sort

The full command is

path=`find /testdir -maxdepth 1 -mindepth 1 -type d | ***Some sort of sort function*** | head -1`

I have a list I want to randomly sort. It works fine in ubuntu but on a 'osx lion' sort dosen't have the --random-sort option.

I don't want to have to install anything is there another way to randomly sort a list?

Cheers in advance

DV

This may not be the most efficient way, but it might work. Assigns a random "key" to each record and then sorts based on the key and strips the key away:

awk 'BEGIN{ srand( ); } { printf( "%.5f %s\n", rand(), $0); }' input-file | sort -k 1n,1 | sed 's/^[^ ]* //'

More specific to your case:

command | awk 'BEGIN{ srand( ); } { printf( "%.5f %s\n", rand(), $0); }' | sort -k 1n,1 | sed 's/^[^ ]* //; 1q'
1 Like

I like it! It seems a bit round the houses.

How would I put that into my command?

path=`find /testdir -maxdepth 1 -mindepth 1 -type d | ***Some sort of sort function*** | head -1`
path=$( find /testdir -maxdepth 1 -mindepth 1 -type d | awk 'BEGIN{ srand( ); } { printf( "%.5f %s\n", rand(), $0); }' | sort -k 1n,1 | sed 's/^[^ ]* //; 1q' )
1 Like

It works... haha!

It would be great to get something a bit simpler but if it works it works!

Cheers

Hi, I know You already have an answer, but the following could be an alternative, insert where You have

***Some sort of sort function***

It's using the same idea but with other programs.

while read line;do echo $RANDOM'|'$line;done |sort|cut -d"|" -f2-

Best regards, Lakris

1 Like