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

kyvafyod  于 2023-04-20  发布在  Linux
关注(0)|答案(3)|浏览(184)

我想生成一个随机数,然后使用该随机数抓取目录中相应的文件,这将反过来创建一个音乐歌曲的随机播放列表。我接受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;
h43kikqp

h43kikqp1#

关于:

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

3vpjnl9f2#

命令head $cnt tail $cnt不正确;你是说head $cnt | tail -1

hc8w905p

hc8w905p3#

你可以用use head -n|尾-1
n是第n个
尝试打印:printf“%s\n”|printf“%s\n”|头-4|tail -1,因此它首先选择前4个文件,然后使用tail -1从这4个文件中选择最后一个,因此选择第4个

相关问题