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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With