I have a file which contains entries numbered 0 to 149. I am writing a bash script which randomly selects 15 out of these 150 entries and create another file from them.
I tried using random number generator:
var=$RANDOM
var=$[ $var % 150 ]
Using var I picked those 15 entries. But I want all of these entries to be different. Sometimes same entry is getting picked up twice. Is there a way to create a sequence of random numbers within a certain range, (in my example, 0-149) ?
You can iterate the sequence of numbers in bash in two ways. One is by using the seq command, and another is by specifying the range in for loop. In the seq command, the sequence starts from one, the number increments by one in each step, and print each number in each line up to the upper limit by default.
Use shuf -i
to generate a random list of numbers.
$ entries=($(shuf -i 0-149 -n 15))
$ echo "${entries[@]}"
55 96 80 109 46 58 135 29 64 97 93 26 28 116 0
If you want them in order then add sort -n
to the mix.
$ entries=($(shuf -i 0-149 -n 15 | sort -n))
$ echo "${entries[@]}"
12 22 45 49 54 66 78 79 83 93 118 119 124 140 147
To loop over the values, do:
for entry in "${entries[@]}"; do
echo "$entry"
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