Best way to choose a random file from a directory in a shell script

后端 未结 11 1589
长情又很酷
长情又很酷 2020-12-13 02:00

What is the best way to choose a random file from a directory in a shell script?

Here is my solution in Bash but I would be very interested for a more portable (non-

11条回答
  •  清歌不尽
    2020-12-13 02:29

    I think Awk is a good tool to get a random number. According to the Advanced Bash Guide, Awk is a good random number replacement for $RANDOM.

    Here's a version of your script that avoids Bash-isms and GNU tools.

    #! /bin/sh
    
    dir='some/directory'
    n_files=`/bin/ls -1 "$dir" | wc -l | cut -f1`
    rand_num=`awk "BEGIN{srand();print int($n_files * rand()) + 1;}"`
    file=`/bin/ls -1 "$dir" | sed -ne "${rand_num}p"`
    path=`cd $dir && echo "$PWD/$file"` # Converts to full path.  
    echo "The randomly-selected file is: $path"
    

    It inherits the problems other answers have mentioned should files contain newlines.

提交回复
热议问题