7

I'm studying AWK, and when I use the following command for the second time why are the numbers always the same?

First time run:

awk 'BEGIN{for(i=1;i<=10;i++) print int(101*rand())}'
24
29
85
15
59
19
81
17
48
15

Second time run:

awk 'BEGIN{for(i=1;i<=10;i++) print int(101*rand())}'
24
29
85
15
59
19
81
17
48
15
2

1 Answer 1

16

From https://www.gnu.org/software/gawk/manual/html_node/Numeric-Functions.html

CAUTION: In most awk implementations, including gawk, rand() starts generating numbers from the same starting number, or seed, each time you run awk. Thus, a program generates the same results each time you run it. The numbers are random within one awk run but predictable from run to run. This is convenient for debugging, but if you want a program to do different things each time it is used, you must change the seed to a value that is different in each run. To do this, use srand().

4
  • 2
    Just be sure to use srand() only once per run, not once per call to rand(). The other pitfall I've seen is to use srand(time()) in a program that could be run more than once in the same second, hence still getting the same seed in all instances started that second.
    – RBerteig
    Mar 12, 2015 at 1:27
  • fore informations, this doesn't happen in mawk 1.3.3
    – c4f4t0r
    May 20, 2015 at 21:46
  • Example (random lines): awk 'BEGIN { srand() }; rand() < 0.01' file.txt
    – miku
    Aug 12, 2016 at 8:36
  • 3
    awk 'BEGIN { "date +%N" | getline seed; srand(seed); print rand(); }'; Using nanoseconds as seed
    – adrianlzt
    Dec 15, 2016 at 8:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .