Pull random line from a file

Conrad Newton conrad.newton at broadpark.no
Fri Sep 6 00:05:39 PDT 2002


On Fri, Sep 06, 2002 at 01:32:40AM +0200, Björn Lindberg wrote:
> Kevan Shea wrote:
> > 
> > I want to pull a random line from a file in a bash script.  I can generate the random number fine, but how would I go about pulling a single line from a file?
> > 
> > I figure this is a one-line sed at worst, but I'm woefully lost by any sed that isn't s/find/replace/ and I can't figure what else I would use... fortune maybe?
> 
> If you know that the random number is not higher than the line count for
> the file, you can do this
> 
> 	line=$(sed -n ${random}p $file)
> 
> where you have the random line number in $random and the filename in
> $file. (Eg 5p is the command for printing the 5th line in sed.)

If you are worried about having too large a random number, try this:

sed -n $[ $RANDOM % $(wc -l < $filename) ]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

-- 
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