将 awk 生成的随机数保存在变量中

save random numbers generated with awk in a variable

此代码在 bash 生成随机数的脚本中非常有用。

awk 'BEGIN {
# seed
srand()
for (i=1;i<=10;i++){
print int(1 + rand() * 1000)
}
}'

但它只是打印随机数。我想将随机数保存在变量中,并在 awk 结束后使用它们。 可能吗?怎么样?

将它们存储在一个数组中,您以后可以重复使用

awk 'BEGIN {
srand();
for (i=1;i<=10;i++){
rdm[i]=int(1 + rand() * 1000)
}
}
END{
for(i=1;i<=10;i++){
print rdm[i]} # reuse them here
}'

如果你想在 awk 之外重用它们:

rdm=($(awk 'BEGIN {
srand()
for (i=1;i<=10;i++){
print int(1 + rand() * 1000)
}
}'))

在bash中:

for r in ${rdm[*]}; do
   echo $r; # or reuse them here
done

Bash 不是我的母语(至少现在还不是 ;),请使用以下代码作为线索:

# uncomment line if for-loop shows numbers as one item
#IFS=$(echo -en "\n\t\b")

# save to var
A=$(awk 'BEGIN {
# seed
srand()
for (i=1;i<=10;i++){
print int(1 + rand() * 1000)
}
}')

# Use in for-loop
for b in $A
do
    echo "Your lucky number is ${b}."
done

# to rolback changes:
#IFS=$(echo -en "\n\t ")

可能会有帮助

IFS - Internal field separator