Generating a Random String of 'n' length

Hi,

How can I generate a string of random characters (alpha+numeric) of a particular length ?

For e.g. for
n=5, output = 'kasjf'
n=10, output = 'hedbcd902k'

Also, please let me know if random (valid) dates could also be generated.

Thanks

This is a linux example for reasonably random dates using /dev/random:
(/dev/urandom gives better random numbers but is overkill for learning)

date -d `echo @ $(od --read-bytes=4 --address-radix=n --format=u4 /dev/random)| awk '{print $1$2}'`

You need to specify a little more background - what UNIX, what shell? In general it is possible especially using perl and awk

... and for a string with a given length:

# length 5
head -3 /dev/urandom | tr -cd '[:alnum:]' | cut -c -5

# length 8
head -3 /dev/urandom | tr -cd '[:alnum:]' | cut -c -8

@Jim, /dev/random gives the better random numbers but is slower than /dev/urandom!

n=6; output=$(tr -cd '[:alnum:]' < /dev/urandom | head -c$n)

$ echo $output
ySezMk

With perl

cat randstring.pl
#!/usr/bin/perl
$n=shift;
@alpha=( ("A".."Z"), ("a".."z") );
@numeric=( (0..9) );
@allchars=( @alpha, @numeric );
$allrange=$#allchars+1;
for ($i=1; $i <=  $n; $i++) {
  $out.=$allchars[int(rand($allrange))];
}
print "$out\n";
./randstring.pl 10

Asuming a length of 10

perl -le 'print map { (a..z,A..Z,0..9)[rand 62] } 0..9'

or:

n=10
perl -le 'print map { (a..z,A..Z,0..9)[rand 62] } 1..pop' $n

Amazing functions!
Only I don't like the 62 .
Applied to my script

cat randstring.pl
#!/usr/bin/perl -l
@allchars=( A..Z, a..z, 0..9 );
print map { @allchars[rand $#allchars+1] } 1..pop

And embedded in a shell script

n=10
perl -le '@allchars=( A..Z, a..z, 0..9 ); print map { @allchars[rand $#allchars+1] } 1..pop' $n