random numbers in awk?
Jonathan I. Kamens
jik at athena.mit.edu
Wed Apr 24 14:11:34 AEST 1991
In article <26019 at adm.brl.mil>, d3e608%pnli.pnl.gov at pnlg.pnl.gov writes:
|> I'm trying to write a csh script to extract a random multiline
|> record from a file. Awk does a nice job of getting the records. Now how
|> do I choose one randomly?
The standard awk has no built-in way of getting a random number.
However, the FSF version of awk, gawk, has a built-in rand() function that
returns a random number between 0 and 1. You can multiply the return value by
the number of records to pick one of them randomly.
If installing and using gawk is not an option, then another possibility is
to use the jot(1) program to generate a random number, if your system has jot.
You would call "jot -r 1 max" where "max" is the number of records from which
you are selecting. Either call this in your script and then pass the result
into awk, or call it inside awk if you've got a version of awk that'll let you
call a program and pipe the results into getline. If you don't have jot, you
can get it from a number of different ftp sites. I found the source to it in
/help/dist/jot.c on lilac.berkeley.edu, and the man page in
/pub/Library/Computer/doc.4.3/ucs/jot.1 on ocf.berkeley.edu, using archie (if
you don't know how to use archie, see the article mentioned in the
instructions appended to the end of this message).
Finally, if you've got access to a version of date(1) that will output the
date as a number of seconds since the beginning of Unix time, then you can
just take that number of seconds as the seed for a random number generator
written inside awk. Your generator can be as symbol for taking the time
modulus the number of records from which you're choosing, or as complex as one
of the good random number generators mentioned in Knuth.
There are probably other ways to get a random number, and other people will
point them out :-).
Of course, if you were using perl instead of awk, you wouldn't need to ask
this question at all, since perl has a built-in function for getting random
numbers, and will have that function on any machine that supports perl.
--
Jonathan Kamens USnail:
MIT Project Athena 11 Ashford Terrace
jik at Athena.MIT.EDU Allston, MA 02134
Office: 617-253-8085 Home: 617-782-0710
--
Subject: Information about finding sources (READ THIS BEFORE POSTING)
Newsgroups: comp.sources.wanted,alt.sources.wanted
Available via anonymous ftp from pit-manager.mit.edu (18.72.1.58)
in the file
/pub/usenet/comp.sources.wanted/Information_about_finding_sources_(READ_THIS_BEFORE_POSTING)
Available from mail-server at pit-manager.mit.edu by sending a message
containing
send usenet/comp.sources.wanted/Information_about_finding_sources_(READ_THIS_BEFORE_POSTING)
Send a message containing "help" to get general information about the
mail server.
More information about the Comp.unix.questions
mailing list