943,825 Members | Top Members by Rank

Ad:
Jun 10th, 2008
0

Random number generator with awk

Expand Post »
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.
Reputation Points: 10
Solved Threads: 0
Light Poster
krammer is offline Offline
26 posts
since Jun 2008
Jun 10th, 2008
0

Re: Random number generator with awk

The range as it stands will run from 0 to 9
So add 1 to it, to get 1 to 10
Team Colleague
Reputation Points: 5862
Solved Threads: 950
Posting Sage
Salem is offline Offline
7,164 posts
since Dec 2005
Jun 10th, 2008
0

Re: Random number generator with awk

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"
Reputation Points: 10
Solved Threads: 0
Light Poster
krammer is offline Offline
26 posts
since Jun 2008
Jun 11th, 2008
0

Re: Random number generator with awk

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
Reputation Points: 75
Solved Threads: 44
Junior Poster
ghostdog74 is offline Offline
156 posts
since Apr 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Shell Scripting Forum Timeline: reading external doc / dir
Next Thread in Shell Scripting Forum Timeline: Newbee: search for folder and add it to PATH





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC