Home > OS >  How can I get a random word from a string in posix shell?
How can I get a random word from a string in posix shell?

Time:12-30

I have an string containing a few words in a posix script:

mystr="word1 word2 word3"

And I want to pick a word randomly. So I ended up doing:

echo "$mystr" | cut -d " " -f "$(shuf -i 1-"$(echo "$mystr" | wc -w)" -n 1)"

This looks so ugly though. Is there a better practice?

CodePudding user response:

Here’s how to use awk to split the string into an array, then print a random element of the array.

echo "word1 word2 word3" |
  awk 'BEGIN { srand() }
             { split($0,a); print a[1 int(rand()*length(a))] }'

Tested on busybox, but ought to work on any POSIX system.

  • Related