bash generate random words

Recently, I needed some random words for test data so I used bash to generate them:

#!/usr/local/bin/bash
# requires bash 4, see http://clubmate.fi/upgrade-to-bash-4-in-mac-os-x/

# load up the dictionary
mapfile dict < /usr/share/dict/words

# count lines in dicitonary
WC=$(cat -n /usr/share/dict/words | wc -l)

# default to 50 words unless user passes param
NUM_WORDS=50
if [ $# -eq 1 ]; then
if echo "$1" | grep -qE ^\-?[0-9]+$; then
NUM_WORDS="$1"
fi
fi

# create file for output
rm -f random_words.txt && touch random_words.txt

# pick random words
for i in `seq 1 $NUM_WORDS`; do
# generate a single number within WC range using jot
RAND_INDEX=$(jot -r 1 1 $WC)
echo ${dict[$RAND_INDEX]} >> random_words.txt
done

Leave a Reply