Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to generate a random string following a specific pattern in Bash

I'm wanting to generate many six character strings all following this pattern:

[consonant][vowel][consonant][consonant][vowel][consonant]

e.g.

haplop
github
qursog

I've looked at various ways of doing this, but nothing I have though of so far is elegant. My thoughts mostly revolved around generating one character at a time but even then my ideas weren't really all that good due to my lack of bash scripting knowledge and obscure Linux commands.

Ideally I'm looking for a Linux command that randomly generates a string but allows me to specify the pattern shown above (if one even exists). Alternatively if you know of a simple way of doing this in bash that would also be great.

Thanks in advance

Edit: BTW, I will give this a 24 hours before choosing the accepted answer so that I have more chance of picking the best answer and not just the first (although the first answer was pretty good).

like image 460
Gerry Avatar asked Aug 11 '11 20:08

Gerry


1 Answers

Here is how you could generate a vowel:

s=aeiou
p=$(( $RANDOM % 5))
c=${s:$p:1}

Use the same method for consonants.

You can wrap this into a small function:

function vowel() {
    s=aeoiu
    p=$(( $RANDOM % 5))
    echo -n ${s:$p:1}
}

And then you have a nice pattern to generate the string:

s=`consonant; vowel; consonant; vowel; consonant; vowel`
like image 132
Karoly Horvath Avatar answered Sep 29 '22 00:09

Karoly Horvath