随机选择一个文件

做选择是很困难的。  有时有这样的需要,一个目录下有一大堆想看的文件,不想记住哪个已经看过了、哪个没有看过,只想快速选择一个文件,而且每个文件被选中的机会是一样的。 于是写了这样一个BASH脚本。  它的基本思路是先生成文件列表,然后产生一个随机数,与文件列表的行号对应,把那行打印出来 。


#! /bin/sh
# randomly choose a file
# Yuwen Dai, 13 September, 2012

# Add file types here
FILE_TYPE="*.mp4 *.flv *.mp3"

# Get the total number of files
TOTAL=`ls -l $FILE_TYPE|wc -l`
TOTAL=$((TOTAL-1))

# Get a random number
R=$((${RANDOM}*${TOTAL}/32767))

# create a temp file
FILE_LIST=`mktemp /tmp/rp_XXXX` || (echo "Create tmp file failed"; exit 1)

# attach a number to each file
for i in ${FILE_TYPE};do
    echo ${TOTAL} ${i} >> ${FILE_LIST}
    TOTAL=$((TOTAL-1))
done

# Get the file name
FILE=`grep "^${R} " ${FILE_LIST}|sed -e "s/^${R} //"`

# delete the temp file
rm ${FILE_LIST}

echo starting play file... 
echo ${FILE}
# we got file, use it whatever you want
#exec mplayer "${FILE}"


其中 $RANDOM 是BASH 环境中的一个随机数,在0到32767之间,然后把它的范围映射到1至文件数目之间。  在文件列表中加上行号, 随机数生成后,找到相应的行,然后打印出文件名。  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章