5

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
15

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 '15 at 1:27
  • fore informations, this doesn't happen in mawk 1.3.3 – c4f4t0r May 20 '15 at 21:46
  • Example (random lines): awk 'BEGIN { srand() }; rand() < 0.01' file.txt – miku Aug 12 '16 at 8:36
  • 3
    awk 'BEGIN { "date +%N" | getline seed; srand(seed); print rand(); }'; Using nanoseconds as seed – adrianlzt Dec 15 '16 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.