randomly shuffling files in bash

2019-01-08 20: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 6
line 7
line 8

and

$cat file2
linea one
linea two
linea three
linea four
linea five
linea six
linea seven
linea eight

And later that i shuffling the two files i can obtain something like:

linea eight
line 4
linea five
line 1
linea three
line 8
linea seven
line 5
linea two
linea one
line 2
linea four
line 7
linea six
line 1
line 6

8条回答
来,给爷笑一个
2楼-- · 2019-01-08 20:43

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
}
查看更多
混吃等死
3楼-- · 2019-01-08 20:54

I would use shuf too.

another option, gnu sort has:

   -R, --random-sort
          sort by random hash of keys

you could try:

cat file1 file2|sort -R
查看更多
登录 后发表回答