Reputation: 63
This code is very helpful awk in bash script for generating random numbers.
awk 'BEGIN {
# seed
srand()
for (i=1;i<=10;i++){
print int(1 + rand() * 1000)
}
}'
But it just print random numbers. I whould like save random number(s) in variable(s) and after awk ends, use them. Is it possible? How?
Upvotes: 0
Views: 1344
Reputation: 21873
Store them in an array which you can reuse later
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
}'
If you want to reuse them outside awk :
rdm=($(awk 'BEGIN {
srand()
for (i=1;i<=10;i++){
print int(1 + rand() * 1000)
}
}'))
and in bash:
for r in ${rdm[*]}; do
echo $r; # or reuse them here
done
Upvotes: 1
Reputation: 2495
Bash isn't my native language (at least not yet ;), use following code as a clue:
# 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 ")
May be helpful
IFS - Internal field separator
Upvotes: 1