随机数的产生与外壳BASH AWK [英] Random numbers generation with awk in BASH shell

查看:120
本文介绍了随机数的产生与外壳BASH AWK的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要洗牌随机文件的线(行),然后打印出不同的五个文件。

但我一直有确切行相同的顺序出现在文件1至file5。随机生成过程不能正常工作。我会为任何建议表示感谢。

 #!/斌/庆典
在序列1 5我

  猫shuffling.txt | awk的'BEGIN {srand()函数;} {打印兰特()\\ t$ 0}'|排序-k2 -k1 -n |切-f2->文件$ i.txt
DONE

输入shuffling.txt

  111 1032192
111 2323476
111 1698881
111 2451712
111 2013780
111 888105
112 2331004
112 1886376
112 1189765
112 1877267
112 1772972
112 574631


解决方案

如果你不提供种子函数srand ,它将使用当前日期和时间。这意味着,如果你的程序运行速度不够快,他们将全部使用相同的种子,并产生相同的序列。

您可以通过使用不同的种子,由外壳提供的解决这个问题。

 在awk -v种子= $ RANDOMBEGIN {函数srand(种子);} {打印兰特(),$ 0}...

$随机提供的号码在每次迭代的变化,让 AWK 程序每次运行得到一个不同的种子

您可以在下面的谈话在行动中看到这一点:

  PAX>因为我在$(SEQ 1 5);做
...> awk的'BEGIN {srand()函数;打印兰特()}
...> DONE
0.0435039
0.0435039
0.0435039
0.0435039
0.0435039PAX>因为我在$(SEQ 1 5);做
...> AWK -v种子= $ RANDOMBEGIN {函数srand(种子);打印兰特()}
...> DONE
0.283898
0.0895895
0.841535
0.249817
0.398753

I wish to shuffle the lines (the rows) of a file at random then print out to different five files.

But I keep having exactly the same order of lines appeared in file1 to file5. The random generation process does not work properly. I would be grateful for any advices.

#!/bin/bash
for i in seq 1 5
do
  cat shuffling.txt | awk 'BEGIN{srand();}  {print rand()"\t"$0}' | sort -k2 -k1 -n | cut -f2-  > file$i.txt
done

Input shuffling.txt

111 1032192
111 2323476
111 1698881
111 2451712
111 2013780
111  888105
112 2331004
112 1886376
112 1189765
112 1877267
112 1772972
112  574631

解决方案

If you don't provide a seed to srand, it will use the current date and time. That means, if your processes run fast enough, they'll all use the same seed and generate the same sequence.

You can get around this by using a different seed, provided by the shell.

awk -v seed=$RANDOM 'BEGIN{srand(seed);}{print rand()" "$0}' ...

The number provided by $RANDOM changes in each iteration so each run of the awk program gets a different seed.

You can see this in action in the following transcript:

pax> for i in $(seq 1 5) ; do
...> awk 'BEGIN{srand();print rand()}'
...> done
0.0435039
0.0435039
0.0435039
0.0435039
0.0435039

pax> for i in $(seq 1 5) ; do
...> awk -v seed=$RANDOM 'BEGIN{srand(seed);print rand()}'
...> done
0.283898
0.0895895
0.841535
0.249817
0.398753

这篇关于随机数的产生与外壳BASH AWK的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆