bash 在bash脚本中创建特定范围内的不同随机数序列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21651014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:30:51  来源:igfitidea点击:

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

bashshell

提问by user3286661

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:

我有一个文件,其中包含编号为 0 到 149 的条目。我正在编写一个 bash 脚本,该脚本从这 150 个条目中随机选择 15 个并从中创建另一个文件。
我尝试使用随机数生成器:

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

使用 var 我选择了这 15 个条目。但我希望所有这些条目都不同。有时,同一条目会被提取两次。有没有办法在一定范围内创建一系列随机数,(在我的例子中,0-149)?

回答by John Kugelman

Use shuf -ito generate a random list of numbers.

使用shuf -i生成数字的随机列表。

$ 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 -nto the mix.

如果您希望它们按顺序排列,则添加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

To loop over the values, do:

要遍历值,请执行以下操作:

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