首页 > 解决方案 > 将文件从一个文件夹复制和粘贴到另一个文件夹,并用随机的非重复数字重命名它们

问题描述

我是 Apple 脚本清理人员,但我想做的是让我的脚本将文件从一个文件夹复制到另一个文件夹,并在此过程中为其分配一个不按时间顺序排列的随机非重复数字。

这是我到目前为止所拥有的:

tell application "Finder"
    
    set destFolder to (make new folder at desktop with properties {name:"NEW BATCH"})
    
    set sourceFolder to (choose folder with prompt "Please select the source images folder")
    
    set numFiles to (number of files of folder sourceFolder)
    
    repeat with i from 1 to numFiles
        
        set newFile to (duplicate some file of folder sourceFolder to destFolder)
        
        set name of newFile to (i & ".jpg" as text)
        
    end repeat
    
end tell

我能够获得复制和粘贴以及为其分配一个数字,但它按时间顺序出现。不知道如何让它得到一个随机数以及不让它重复。

标签: iosbashapplescript

解决方案


当然,它是按时间顺序出现的,因为您使用的是连续循环。

首先,您必须创建一个带有索引号的列表。为了避免重复的索引号,获取一个随机整数并将some integer给定索引处的项目设置为missing value

tell application "Finder"
    set destFolder to make new folder at desktop with properties {name:"NEW BATCH"}
    set sourceFolder to choose folder with prompt "Please select the source images folder"
    set numFiles to number of files of folder sourceFolder
end tell

set indexNumbers to {}

repeat with i from 1 to numFiles
    set end of indexNumbers to i
end repeat

repeat numFiles times
    set randomIndex to some integer of indexNumbers
    set item randomIndex of indexNumbers to missing value
    tell application "Finder"
        set newFile to (duplicate file randomIndex of folder sourceFolder to destFolder)
        set fileExtension to name extension of newFile
        set name of newFile to ((randomIndex as text) & "." & fileExtension)
    end tell
end repeat

推荐阅读