根据文件夹中的文件名执行特定操作

Doing a certain action based on the name of a file in a folder

我正在制作一个脚本来整理我的桌面。例如,如果我将文件另存为 "English Questions.docx",脚本会在其名称中选取单词 "English" 并将其移动到我的 "English" 文件夹中。所以我需要知道:

  1. 如何查找桌面上所有文件的名称
  2. 如何根据名称将这些文件移动到特定文件夹

谢谢。

我认为下面的脚本可以解决您的问题。

1) 搜索将仅限于桌面内的文件夹(和任何子文件夹)。

2) 如果文件名由 x 个单词组成,则将对 3 个单词中的每一个进行搜索。示例文件 "English Apple File.docx",脚本将尝试查找文件夹 "English"、文件夹 "Apple" 和文件夹 "File"。在每种情况下,如果找到该文件夹​​,就会完成移动。

警告:在此示例中,如果 3 个文件夹存在,脚本将出现问题,因为从桌面移动到文件夹 "English" 后,该文件不再存在于桌面中(然后无法再次移动到文件夹 "Apple"。如果您希望文件在 3 个文件夹中的每一个中都是重复的,我们应该在脚本中使用 'duplicate' 指令而不是 'move'。

这是脚本:我添加了很多注释以确保您理解每一行的含义并且您能够自己进行调整。

技巧是使用'mdfind' shell命令搜索,使用spotlight引擎,桌面文件夹内任意一级文件夹。

set myDesktop to path to desktop from user domain
tell application "Finder" to set FileList to every file of myDesktop whose kind is not in {"Alias", "Application"}

repeat with aFile in FileList
tell application "Finder"
    set FName to name of aFile
    set FExt to name extension of aFile
end tell
set onlyName to text 1 thru -((length of FExt) + 2) of FName -- get file name without extension
set Mywords to every word of onlyName -- extract every words of the file name

repeat with MyTarget in Mywords --loop through each word
    set TheResult to do shell script "mdfind -name " & MyTarget & " 'kind:folder' -onlyin ~/Desktop"
    if TheResult is "" then
        -- folder not found with that word
        display dialog "Folder " & MyTarget & " not found in Desktop !"
    else
        if (count of paragraph of TheResult) > 1 then
            -- there are many folders matching that word: what to do ?
            display dialog "There are " & (count of paragraph of TheResult) & " folders named " & MyTarget
        else
            -- only 1 folder match the word : lets move the file to that folder!
            set DestFolder to POSIX file ((TheResult & "/") as string)
            try
                tell application "Finder" to move aFile to DestFolder
            end try
            -- if you want to delete file from source folder after the move !!
            -- tell application "Finder" to delete aFile
        end if --if count of paragraph > 1
    end if -- if TheResult = ""
end repeat -- to next words of the file name
end repeat -- to next file in the list