My script produces the same output when using $RANDOM

It doesn't. But $RANDOM returns big numbers (between 0 and 32767) which, especially for words of limited lengths, shows the same result, as the head portion probably returns all the results of the grep (for 3, there are only 819 matches in my /usr/share/dict/words).

Better solution might be to shuffle the results:

egrep "^.{$num}$" /usr/share/dict/words | sort -R | tail -n 1

where -R means --random-sort (a GNU sort extension).


A simple method to print an arbitrary num-letter word uses shuf:

egrep "^.{$num}$" /usr/share/dict | shuf -n1

The shuf command outputs a random permutation of the input, and the -n1 flag tells it to only output the first item from this result.


As others have pointed out, the main issue with your code is that $RANDOM more often than not is going to be a value much larger than then number of words of a certain length.

Using awk only:

$ awk -v len="$num" 'length == len { word[i++]=$0 }
                     END { print word[int(i*rand())] }' /usr/share/dict/words
Bosniac

The program reads in all lines from the given file that are of a certain length. These are stored in the array words.

At the end, a random element from this array is selected and printed.

Tags:

Bash

Random