Random ordering

1
2
4
5
3

I would like to use a script so that i can randomly rearrange these numbers such as

3
5
2
4
1

Thanks!

You could try shuf filename or sort --random-sort filename

1 Like

Here is a script that I found on BashFaQ using Knuth-Fisher-Yates shuffle algorithm.

#!/bin/bash

# Uses a global array variable.  Must be compact (not a sparse array).
# Bash syntax.
shuffle() {
   local i tmp size max rand

   # $RANDOM % (i+1) is biased because of the limited range of $RANDOM
   # Compensate by using a range which is a multiple of the array size.
   size=${#array[*]}
   max=$(( 32768 / size * size ))

   for ((i=size-1; i>0; i--)); do
      while (( (rand=$RANDOM) >= max )); do :; done
      rand=$(( rand % (i+1) ))
      tmp=${array} array=${array[rand]} array[rand]=$tmp
   done
}

# Define the array named 'array'
array=( '1' '2' '3' '4' '5')

shuffle
printf "%s\n" "${array[@]}"

try also:

awk '{a[$0]=$0} END {for (i in a) print i}' infile