Home > Mobile >  Generate a random sequence of two words
Generate a random sequence of two words

Time:10-05

How can I generate a random sequence of two words?

E.g. I want output like

act apt act act apt act act apt apt apt apt act

for words "apt" and "act" and sequence length 12

I came up with

 repeat 12 { if [ $(($(($RANDOM))%2)) -eq 1 ] ; then echo act ; else echo apt ; fi }

but it is quite long, especially the coin toss, is there a more elegant way?

CodePudding user response:

With shuf from GNU coreutils (in my case version 8.32):

shuf -r -n 12 -e act apt | tr '\n' ' '

From man shuf:

shuf - generate random permutations
-e, --echo : Treat each ARG as an input line
-r, --repeat : Output lines can be repeated
-n, --head-count=COUNT : Output at most COUNT lines

shuf alone prints one word per line, so we use tr to put all words into a single line by replacing the linebreaks by spaces.

  • Related