2014-12-04 42 views
0

我想生成一個隨機數,然後使用該隨機數來抓取目錄中的相應文件,這將隨後創建音樂歌曲的隨機播放列表。我採用3個參數,音樂路徑,新播放列表的名稱以及播放列表中要播放的歌曲數量。出於某種原因,在while循環它複製多個文件,而不是僅僅是第n個隨機文件的每一次迭代試圖將目錄中的第n個文件複製到另一個文件夾

#!/bin/bash 

#accepts 3 arguments path to music, name of the new playlist, and amount of songs you want in   the playlist 
path_to_music=$1; 
playlistname=$2; 
count=$3; 

#finds number of songs in directory, allows for more effective randomness 


#cd to the path where music is 
if [ -d "$path_to_music" ]; 
then 
    eval cd $path_to_music 
    numOfFiles=$(find . -type f | wc -l) 
else 
    echo "Directory does not exist, enter correct path." 
    read path_to_file 
fi 

ran=$[ ($RANDOM % 5) + 1 ] 
let ran=numOfFiles-ran; 
#make new folder where music is, will contain random songs (new playlist) 
mkdir $playlistname 

i=1 
while : #while loop finds a random song and copies it to folder created, $cnt is randomly generated so songs are random 
do 
    if [ "$i" -ne "$count" ]; 
    then  
     cnt=$[ ($RANDOM % 34) + 1 ] 
     let "cnt*=(-1)" 
     find -type f | head $cnt tail $cnt | xargs -I % cp % $path_to_music/$playlistname ; 
     let "i+=1" 
     echo $i 
    else 
     break; 
    fi 
done; 
+1

'head $ cnt tail $ cnt'在兩者之間缺少'|'。 'eval cd $ path_to_music'是* evil *。只要放下'eval',引用變量並且用'〜'住不起作用。 – 2014-12-04 18:51:15

回答

1

什麼:

printf '%s\n' * | shuf | head -1 | xargs -I% cp % /another/dir/% 
+0

或者甚至是'cp $(printf'%s \ n'* | shuf -n 1)/ another/dir/.',以消除一些額外的不必要的步驟... – twalberg 2014-12-04 20:19:30

+0

@twalberg:當文件名包含空格時, ... – 2014-12-05 17:03:44

0

命令head $cnt tail $cnt是畸形的;你的意思是head $cnt | tail -1

相關問題