LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Printing random lines of a file (https://www.linuxquestions.org/questions/linux-software-2/printing-random-lines-of-a-file-465771/)

jrdioko 07-20-2006 12:05 AM

Printing random lines of a file
 
I've been using the remind program to print reminders for various things, and it's usually pretty straightforward to use, but I've run into something I can't figure out how to do. I'd like to be able to get a reminder that is one randomly picked from a long list, rather that something I've scheduled for that specific day. It looks like remind can call a remote program, so I guess it boils down to needing something that will take a file, pick a given number of random lines from that file, and print them out. Any ideas?

puffinman 07-20-2006 12:36 AM

I happen to have already written just such a program, which I use to pick random words from a dictionary file. It should be self explanatory and I hope it helps!

Code:

#!/usr/bin/perl
use Tie::File;
use Fcntl 'O_RDONLY';

my $dict = shift || '/usr/share/dict/words';
my $times = shift || 1;

if ($times == 1) {

  sysopen(DICTIONARY,$dict,O_RDONLY);
  rand($.) < 1 && ($word = $_) while <DICTIONARY>;
  print $word;

} else {

  tie @f, 'Tie::File', $dict, mode => O_RDONLY
    or die "Couldn't open $dict: $!\n";
  my $size = scalar @f;
  $\ = "\n";

  while ($times--) {
    print $f[rand $size];
  }
}


spooon 07-20-2006 12:42 AM

a related questions is answered in perlfaq5

archtoad6 07-20-2006 09:00 AM

I like the algorithm from the Camel Book.

Any interest in trying to it as a bash script? I think this might work (WARNING -- I have tested the pieces, but not the whole):
Code:

#!/bin/bash

N=1
F="path_to_default_reminder_file"

[ $1 -gt 0 ] && N=$1
[ -f $2 ]    && F=$2

C=`wc -l $F`


for ((I=1; $I<=$N; I++))
do
  L=$((RANDOM%$C))
  sed -n "${L}p" $F
done

Mild apologies for the 1 letter variables, old habit that dies hard. (Yes, reinforced by BASIC, but not learned there.)


All times are GMT -5. The time now is 03:54 PM.