The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
Google UNIX.COM



Thread: Random
View Single Post in UNIX Forums - Click on the Thread or Permalink to View Entire Thread -->
  #4 (permalink)  
Old 05-24-2007
aigles's Avatar
aigles aigles is offline
Registered User
 

Join Date: Apr 2004
Location: Bordeaux, France
Posts: 1,212
You can store all the words in a file (assume words.txt).
Code:
stored_word()
{
   if [ -z "$stored_words_count" ]
   then
      stored_words_count=$(wc -l < words.txt)
   fi
   number=$RANDOM
   let "number = number % stored_words_count + 1"
   tail +$number words.txt | head -1
}
Another solution is to read the file into an array.
Code:
init_stored_words()
{
   while read w
   do
      words[${#words[@]}]=$w
   done < words.txt
   stored_words_count=${#words[@]}
}
stored_word()
{
   [ -z "$stored_words_count" ] && init_stored_words
   number=$RANDOM
   let "number %= stored_words_count"
   echo  ${words[$number]}
}
Jean-Pierre.

Last edited by aigles; 05-24-2007 at 09:31 AM.. Reason: Modify number calculation for tail/head solution.
Reply With Quote