Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting x random values from a bash array

Tags:

arrays

bash

I have an array in Bash, say it contains the numbers {1, 2, 3, 4, 5}. I want to extract some of those numbers randomly, such that the same number doesn't get extracted twice.

Basically, if I wanted to extract 3 numbers from the array, I want results like: {3, 4, 1} or {5, 2, 4} and not {1, 1, 3} or {2, 5, 2}.

I've tried deleting elements as I extract them, but it always seems to mess up. Can anyone help?

like image 743
Rsaesha Avatar asked Jul 28 '11 12:07

Rsaesha


1 Answers

Decided to write an answer, as I found the --input-range option to shuf that turned out handy:

N=3
ARRAY=( zero one two three four five )

for index in $(shuf --input-range=0-$(( ${#ARRAY[*]} - 1 )) -n ${N})
do
    echo ${ARRAY[$index]}
done
like image 151
Anders Lindahl Avatar answered Oct 13 '22 19:10

Anders Lindahl