Wednesday, February 29, 2012

Generate Word With Random Characters In Linux

Using following simple bash command we can generate words with random characters.
tr -dc a-z < /dev/urandom | head -c 10 | xargs
This will generate a word with 10 random characters (letter). The random characters will be from a-z.

To add other characters as seed, for eg: A-Z, run
tr -dc a-zA-Z < /dev/urandom | head -c 10 | xargs
As you might have figured out, you can add characters as parameters to tr command. And hence,
tr -dc a-zA-Z0-9 < /dev/urandom | head -c 10 | xargs
will generate words that will include digits as well.

Similarly we can include underscore or other symbols as
tr -dc a-zA-Z0-9_- < /dev/urandom | head -c 10 | xargs
To generate different number of characters we can change the parameter to head command. In all of the above examples value 10 was given and hence 10 characters word.
tr -dc a-zA-Z0-9_- < /dev/urandom | head -c 5 | xargs
will generate 5 random characters word.

We can even put this command in a script file and give number of characters as run time parameter.
while :
tr -dc a-z < /dev/urandom | head -c ${1} | xargs
./scriptname numberOfCharacters
will produce infinite number of words with numberOfCharactersletter in each of them.

However the algorithm isn't very fast one.

1 comment: