Randomly shuffling lines in Linux / Bash

前端 未结 8 2061
囚心锁ツ
囚心锁ツ 2020-12-01 04:16

I have some files in linux. For example 2 and i need shuffling the files in one file.

For example

$cat file1
line 1
line 2
line 3
line 4
line 5
line          


        
相关标签:
8条回答
  • 2020-12-01 05:00

    This worked for me. It employs the Fisher-Yates shuffle.

    randomize()
    {   
        arguments=("$@")
        declare -a out
        i="$#"
        j="0"
    
    while [[ $i -ge "0" ]] ; do
        which=$(random_range "0" "$i")
        out[j]=${arguments[$which]}
        arguments[!which]=${arguments[i]}
        (( i-- ))
        (( j++ ))
    done
    echo ${out[*]}
    }
    
    
    random_range()
    {
        low=$1
        range=$(($2 - $1))
        if [[ range -ne 0 ]]; then
            echo $(($low+$RANDOM % $range))
        else
            echo "$1"
        fi
    }
    
    0 讨论(0)
  • 2020-12-01 05:02

    It is clearly biased rand (like half the time the list will start with the first line) but for some basic randomization with just bash builtins I guess it is fine? Just print each line yes/no then print the rest...

    shuffle() {
        local IFS=$'\n' tail=
        while read l; do
            if [ $((RANDOM%2)) = 1 ]; then
                echo "$l"
            else
                tail="${tail}\n${l}"
    
            fi
        done < $1
        printf "${tail}\n"
    }
    
    0 讨论(0)
提交回复
热议问题