Pull random line from a file

Kevan Shea biffcool at zombieworld.com
Fri Sep 6 08:18:39 PDT 2002


On Fri, 6 Sep 2002 09:34:36 +0200, Conrad Newton <conrad.newton at broadpark.no> wrote:
> Sorry, in my previous post, I had an off by 1 error!
> 
> If you are worried about having too large a random number, try this:
> 
> sed -n $[ $RANDOM % $(wc -l < $filename) + 1 ]p $filename
> 
> Notice that RANDOM is defined in bash.  From the info file 
> 
> - Each time this parameter is referenced, 
>   a random integer between 0 and 32767 is generated.
>      
> Conrad

Yeah that's sort of what I'm doing.  Found $RANDOM accidentally by trying to name a flag in the script $RANDOM, that was confusing for a second or ten.

For completeness heres the end script:

NUMLINES=`grep -c --regexp=.* $FILENAME`
NUM=`expr $RANDOM % $NUMLINES + 1`
RNDLINE=`sed -n ${NUM}p $FILENAME`

Thanks guys

-- 
Kevan Shea



-- 
Unsubscribe: send email to listar at linuxfromscratch.org
and put 'unsubscribe lfs-chat' in the subject header of the message



More information about the lfs-chat mailing list