[NTLUG:Discuss] Bash script question

Lance Simmons lance at lsimmons.net
Wed Jan 19 16:52:13 CST 2005


* Patrick R. Michaud <pmichaud at pobox.com> [050119 15:08]:
> 
> 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

Thanks.  This is what I settled on:

	#!/bin/sh
	
	file="$1"
	loops="$2"
	
	COUNT=$(wc -l <$file)
	
	for i in $(seq 1 "$loops")
	do
		LINE=$(($RANDOM % $COUNT + 1));
»·······head -$LINE $file | tail -1
	done

-- 
Lance Simmons



More information about the Discuss mailing list