| | |
Random number generator with awk
![]() |
•
•
Join Date: Jun 2008
Posts: 26
Reputation:
Solved Threads: 0
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?
Thanks to anyone who can help.
Shell Scripting Syntax (Toggle Plain Text)
#!/bin/bash RANGE=10 number=$RANDOM let "number %= $RANGE" NAME=$(awk 'NR=='$number'{print;exit}' /home/names) echo "$NAME"
Thanks to anyone who can help.
•
•
Join Date: Jun 2008
Posts: 26
Reputation:
Solved Threads: 0
Thanks!
Shell Scripting Syntax (Toggle Plain Text)
#!/bin/bash RANGE=10 number=$RANDOM let "number %= $RANGE" NAME=$(awk 'NR=='$number+1'{print;exit}' /home/eric/names) echo "$NAME"
•
•
Join Date: Apr 2006
Posts: 148
Reputation:
Solved Threads: 40
do it using awk's srand() and rand().
Shell Scripting Syntax (Toggle Plain Text)
awk 'BEGIN{ srand() num=int(rand() * 10) + 1 } NR==num' file
![]() |
Other Threads in the Shell Scripting Forum
- Previous Thread: reading external doc / dir
- Next Thread: Newbee: search for folder and add it to PATH
| Thread Tools | Search this Thread |






