Thursday, October 28, 2021

[SOLVED] AWK -- Select Random Record From A List

Issue

I am trying to return a random word from /usr/share/dict/words on my *NIX machine. I have written the following script using BASH, AWK, and SED together to do it, but I feel like it should be writable using AWK alone by using the RN and NF fields somehow.

#!/bin/bash

get_secret_word () {
    awk '/^[A-Za-z]+$/ {if (length($1) > 3 && length($1) < 9) 
        print $1}' /usr/share/dict/words > /tmp/word_list
    word_list_length=$(wc -l /tmp/word_list | awk '{print $1}')
    random_number=$(( $RANDOM%$word_list_length ))
    secret_word=$(sed "${random_number}!d" /tmp/word_list)
    return $secret_word
}
get_secret_word
echo $secret_word

Any suggestions? I love AWK, and I'm trying to understand it better.


Solution

Try something like:

awk '
BEGIN {
    srand('"$RANDOM"')
}
{
    if (/^[A-Za-z]+$/ && length() > 3 && length() < 9)
        words[i++] = $1
}
END {
    print words[int(rand() * i)]
}' /usr/share/dict/words

Whether you store the words in memory or in a file will depend on your use case.
BR.



Answered By - tshiono