Pull random line from a file

Scot Mc Pherson scot at linuxfromscratch.org
Fri Sep 6 10:46:25 PDT 2002


On Fri, 06 Sep 2002 13:39:07 -0400, Scot Mc Pherson wrote:

> On Thu, 05 Sep 2002 18:16:23 -0400, 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?
>  
> that's easy...lets say that your random number is assigned to variable
> $i
> 
> the syntax would be:
> 
> sed -n /^.*$/s///${i}p inputfile > outputfile
> 
> which says:
> 
> -n = supress output ..  find pattern ^.*$ ( all whole lines  .. whihch
> means every line) and switch ""  for "" which mean change nothing .. on
> the ${i}th line ... and p = print the pattern space that is matched.
> 
> You'll have to test it, but that should do it.
> 
> Scot Mc Pherson
 
actually in relection that's wrong...

sed -n s/^.*$/&/${i}p in > out

thats what you want...because the ${i} will refer to the number of
instances of what here >>   //s/*//   not here >>  /*/s///

so $ sed -n s/^.*$/&/${i}p   means switch a whole line (^.*$)  with an
exact match ( & ) and print the output.  the ${i} still refers the the
nth instance

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