Creating a sequence of individual random numbers in a specific range in a bash script

I have a file containing records with numbers from 0 to 149. I am writing a bash script that randomly selects 15 of these 150 records and creates another file from them.
I tried using a random number generator:

var=$RANDOM
var=$[ $var % 150 ]

Using var, I selected these 15 entries. But I want all these records to be different. Sometimes the same record gets twice. Is there a way to create a sequence of random numbers in a specific range (in my example, 0-149)?

+4
source share
1 answer

Use shuf -ito 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

, sort -n .

$ 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

, :

for entry in "${entries[@]}"; do
    echo "$entry"
done
+8

Source: https://habr.com/ru/post/1525963/


All Articles