1752743 Members
4854 Online
108789 Solutions
New Discussion юеВ

Re: Random alphanumeric?

 
SOLVED
Go to solution
Chua Wen Ching
Regular Advisor

Random alphanumeric?

I am using HP-UX 10.20. I use echo $RANDOM to random generate numbers. But if i want to random generate alphabets or alphanumeric (ex: 2 characters). Can is still use $RANDOM???
wenching
14 REPLIES 14
harry d brown jr
Honored Contributor
Solution

Re: Random alphanumeric?

echo `expr $RANDOM % 26` `expr $RANDOM % 26` | awk '{alphabet = "abcdefghijklmnopqrstuvwxyz"; printf("%s%s\n", substr(alphabet,$1,1), substr(alphabet,$2,1)); }'


live free or die
harry
Live Free or Die
Chua Wen Ching
Regular Advisor

Re: Random alphanumeric?

The above code is used to random generate alphabets. Is there any way to random generate alphanumerics? Thank you.
wenching
Pete Randall
Outstanding Contributor

Re: Random alphanumeric?

I'm sure there's a better way but a crude method would be to combine Harry's alphabetic code with "echo ${RANDOM}".

Pete

Pete
harry d brown jr
Honored Contributor

Re: Random alphanumeric?


Sure, and I'll include upper/lower case:

echo `expr $RANDOM % 62` `expr $RANDOM % 62` | awk '{alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; printf("%s%s\n", substr(alphabet,$1,1), substr(alphabet,$2,1)); }'


live free or die
harry
Live Free or Die
Pete Randall
Outstanding Contributor

Re: Random alphanumeric?

And that's much more elegant than anything I could have come up with - nice one, Harry!

Pete

Pete
Chua Wen Ching
Regular Advisor

Re: Random alphanumeric?

Thanks a lot. It really help a lot.
wenching
H.Merijn Brand (procura
Honored Contributor

Re: Random alphanumeric?

Much too complicated :)

Only able to reply now. This morning I was redirected to the US :(

PC03:/W 501 $ perl -le 'print +("A".."Z",0..9,"a".."z")[int rand 62]'
J
PC03:/W 502 $ perl -le 'print +("A".."Z",0..9,"a".."z")[int rand 62]'
U
PC03:/W 503 $ perl -le 'print +("A".."Z",0..9,"a".."z")[int rand 62]'
X
PC03:/W 504 $ perl -le 'print +("A".."Z",0..9,"a".."z")[int rand 62]'
U
PC03:/W 505 $ perl -le 'print +("A".."Z",0..9,"a".."z")[int rand 62]'
9
PC03:/W 506 $ perl -le 'print +("A".."Z",0..9,"a".."z")[int rand 62]'
6
PC03:/W 507 $ perl -le 'print +("A".."Z",0..9,"a".."z")[int rand 62]'
D
PC03:/W 508 $
Enjoy, Have FUN! H.Merijn
harry d brown jr
Honored Contributor

Re: Random alphanumeric?

procura,

I agree that I'd personally do this in perl and not a shell. perl rules and shells smell!

live free or die
harry
Live Free or Die
Chua Wen Ching
Regular Advisor

Re: Random alphanumeric?

Dear procura, thank you for your code. But i think my org unix is using an old perl interpreter. When i perl -v, it display perl version 4.0. I always trys your perl code, but it never works. I only see 5 everytime i execute your code. Is perl really that powerful? Any good tutorial on perl? Thank you.
wenching