Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a sequence of distinct random numbers within a certain range in bash script

Tags:

bash

shell

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) ?

like image 844
nishantsingh Avatar asked Feb 08 '14 19:02

nishantsingh


People also ask

How do you set a range of numbers in bash?

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.


1 Answers

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
like image 61
John Kugelman Avatar answered Oct 04 '22 15:10

John Kugelman