Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

$RANDOM from file

Status
Not open for further replies.

krammer

IS-IT--Management
Jul 15, 2007
59
US
After the last post, I was interested in playing around with "awk." What I am trying to do now is choose a random number, and have "awk" use that random number for the line it will chose from a text file. What is happening is I am getting a constant loop of the whole text file...I got the code from " it the count that is doing this?

Code:
#!/bin/bash


MAXCOUNT=10
count=1
while [ "$count" -le $MAXCOUNT ] 
do
number=$RANDOM
NAME=$(cat /home/eric/names | /usr/bin/awk '{print $number}')
echo $NAME

done
 
In your shell man pages have a look at quoting.
Furthermore: man awk

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Well, you aren't counting at all. So congratulations on your first[green]?[/green] infinite loop. ;-)


HTH,

p5wizard
 
Yeah I didn't really want to count lol...

PHV - Single quotes are stronger than double quotes...That's all I really found when researching them...but I did play around with it. This works, and is what I was trying to do...but I don't know if its the best way or why it really works with the single quotes:

Code:
RANGE=10
number=$RANDOM
let "number %= $RANGE"
NAME=$(cat /home/eric/names | /usr/bin/awk {'print $'$number''})
echo "$NAME"
 
Just for us UUOC pedants try
Code:
NAME=$(/usr/bin/awk '{print $'$number'}' /home/eric/names)

On the internet no one knows you're a dog

Columb Healy
 
:)

It was useless wasn't it...thanks!
 
Replacing this:

Code:
NAME=$(/usr/bin/awk '{print $'$number'}' /home/eric/names)

With this:

Code:
NAME=$(awk 'NR=='$number+1'{print;exit}' /home/eric/names)

Is much more accurate for how my text file is formatted, and it fixes getting numbers 1-10, instead of 0-9.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top