Random number generator with awk

Reply

Join Date: Jun 2008
Posts: 26
Reputation: krammer is an unknown quantity at this point 
Solved Threads: 0
krammer krammer is offline Offline
Light Poster

Random number generator with awk

 
0
  #1
Jun 10th, 2008
I am trying to print a random line from a text file that has 10 lines. The problem that I run into is that it sometimes picks the number "0" which is not a line in the text file. How would I have it pick a random number between 1-10?

Shell Scripting Syntax (Toggle Plain Text)
  1. #!/bin/bash
  2.  
  3. RANGE=10
  4. number=$RANDOM
  5. let "number %= $RANGE"
  6. NAME=$(awk 'NR=='$number'{print;exit}' /home/names)
  7. echo "$NAME"

Thanks to anyone who can help.
Reply With Quote Quick reply to this message  
Join Date: Dec 2005
Posts: 5,850
Reputation: Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute Salem has a reputation beyond repute 
Solved Threads: 749
Team Colleague
Salem's Avatar
Salem Salem is offline Offline
Void main'ers are DOOMed

Re: Random number generator with awk

 
0
  #2
Jun 10th, 2008
The range as it stands will run from 0 to 9
So add 1 to it, to get 1 to 10
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 26
Reputation: krammer is an unknown quantity at this point 
Solved Threads: 0
krammer krammer is offline Offline
Light Poster

Re: Random number generator with awk

 
0
  #3
Jun 10th, 2008
Thanks!

Shell Scripting Syntax (Toggle Plain Text)
  1. #!/bin/bash
  2.  
  3. RANGE=10
  4. number=$RANDOM
  5. let "number %= $RANGE"
  6. NAME=$(awk 'NR=='$number+1'{print;exit}' /home/eric/names)
  7. echo "$NAME"
Reply With Quote Quick reply to this message  
Join Date: Apr 2006
Posts: 148
Reputation: ghostdog74 is on a distinguished road 
Solved Threads: 40
ghostdog74 ghostdog74 is offline Offline
Junior Poster

Re: Random number generator with awk

 
0
  #4
Jun 11th, 2008
do it using awk's srand() and rand().
Shell Scripting Syntax (Toggle Plain Text)
  1. awk 'BEGIN{
  2. srand()
  3. num=int(rand() * 10) + 1
  4. }
  5. NR==num' file
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the Shell Scripting Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC