Scramble words

If I have a file like:

one two three four five six seven eight nine ten eleven twelve thirteen

How can I use bash to scramble the words randomly, so that the sequence becomes different?

I am talking about something like:

four eight eleven two one thirteen ...

Maybe not the best solution, but for something in pure shell, and a few minutes effort, it'll at lest serve as an example:

#!/usr/bin/env ksh
# or for bash put next line at top
#!/usr/bin/env bash

while read line
do
    typeset -a words=($line)  # tokens from line into a work array
    have=${#words[@]}         # number of words this line
    used=0                    # number we've printed
    while (( $used < $have ))   # while we still have words to do
    do
        n=$(( $RANDOM % $have ))   # pick a word 
        while (( $n < $have )) && [[ ${words[$n]} == "" ]]  # if we've used it find next unused word
        do
            n=$(( $n + 1 ))
            if (( $n > $have - 1 ))  # wrap to beginning if needed
            then
                n=0
            fi
        done

        printf "%s " ${words[$n]}    # print the random choice 
        words[$n]=""                  # prevent word from being reused
        used=$(( $used + 1 ))
    done

    printf "\n"
done

This reads lines from standard input and 'scrambles' the words on the line.

1 Like