尝试将目录中的第n个文件复制到另一个文件夹

时间:2014-12-04 18:48:56

标签: linux bash shell unix

我想生成一个随机数,然后使用该随机数来获取目录中的相应文件,这将依次创建音乐歌曲的随机播放列表。我采用3个参数,音乐路径,新播放列表的名称以及播放列表中您想要的歌曲数量。出于某种原因,在while循环的每次迭代中,它都会复制多个文件,而不仅仅是第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; 

2 个答案:

答案 0 :(得分:1)

怎么样:

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

答案 1 :(得分:0)

命令dim studata dim len len = Len( Session( "stuDataCode" )) studata = Session( "stuDataCode" ) 格式不正确;你的意思是head $cnt tail $cnt