[NTLUG:Discuss] Bash script question

Patrick R. Michaud pmichaud at pobox.com
Wed Jan 19 14:45:37 CST 2005


On Wed, Jan 19, 2005 at 02:09:47PM -0600, Lance Simmons wrote:
> Let's say I have 100 names in a file.  I want to randomly select a name
> from the file, add it to a list, and repeat that process 40 times.  The
> result of the process should be a list of 40 names in random order, some
> of which may repeat in the list.
> [...]
> Does anyone have any suggestions?

How about something like:

   for i in $(seq 1 40)
   do
       LINE=$(($RANDOM % 100 + 1));
       head -$LINE infile | tail -1
   done

The outer loop just counts from 1 to 40.  The inner portion of the loop grabs
one line at random from infile, by first computing a random number between
1 and 100, and then extracting the corresponding line of the file.

If you want to get rid of the hardcoded "100", so that you don't have
to know the number of lines in advance, you can use:

   COUNT=$(wc -l <infile)
   for i in $(seq 1 40)
   do
       LINE=$(($RANDOM % $COUNT + 1));
       head -$LINE infile | tail -1
   done

This is far from the most efficient way of doing it, but it works
in bash.  Faster would be to use a short perl script to do it 
(I can provide this also if you want).

Pm



More information about the Discuss mailing list