Applescript - 递归搜索目录

时间:2016-05-10 21:44:30

标签: macos recursion applescript

我有一个由其他用户慷慨创建的脚本,但我发现它不会通过目录递归读取。该脚本的目标是读取在Finder中选择的目录的所有子目录,并写出255个字符或更长的文件的绝对路径(路径不是文件名)。这是为了在具有255个字符路径限制的Windows机器上找到OSX上绝对路径长度太长的文件,然后再将它们从一个传输到另一个。

我已尝试引用此帖子以使其递归,但无效,因为此处的方法显示完全不同:AppleScript Processing Files in Folders recursively

on run
set longPaths to {}
tell application "Finder" to set theSel to selection
repeat with aFile in theSel
    set aFile to aFile as string
    set pathLength to count of characters in aFile
    if pathLength > 255 then
        set end of longPaths to aFile
    end if
end repeat

if longPaths is not equal to {} then
    -- do something with your list of long paths, write them to a text file or whatever you want
    set pathToYourTextFile to (path to desktop folder as string)&"SampleTextFile.txt"
    set tFile to open for access file (pathToYourTextFile as string) with write permission
    repeat with filePath in longPaths
        write (filePath & return as string) to tFile starting at eof
    end repeat
    close access tFile
end if
end run

有没有人知道向此脚本添加递归元素的最佳方法,以便theSel包含所选目录的子目录中的所有文件?

2 个答案:

答案 0 :(得分:0)

尝试:

tell application "Finder" to set theSel to every file in (get entire contents of selection)

或类似的东西。对不起,我没有Mac来测试精确的代码。每当您要求entire contents时,您将获得所选文件夹的所有子文件夹中的所有内容。

答案 1 :(得分:0)

这是一个通过目录递归读取的脚本:

property theOpenFile : missing value

tell application "Finder" to set theSel to selection
if theSel is not {} then
    set pathToYourTextFile to (path to desktop folder as string) & "SampleTextFile2.txt"
    set theOpenFile to open for access file (pathToYourTextFile as string) with write permission
    repeat with aItem in theSel
        tell application "Finder" to class of aItem is folder
        if the result then my getFilesIn(aItem) -- aItem is a folder
    end repeat
    close access theOpenFile
end if

on getFilesIn(thisFolder)
    tell application "Finder" to set theseFiles to files of thisFolder as alias list
    repeat with thisFile in theseFiles
        set f to thisFile as string
        set pathLength to length of f
        if pathLength > 255 then my writeToFile(f)
    end repeat
    tell application "Finder" to set theseSubFolders to folders of thisFolder
    repeat with tSubF in theseSubFolders
        my getFilesIn(tSubF) -- call this handler (recursively through this folder)
    end repeat
end getFilesIn

on writeToFile(t)
    write (t & return) to theOpenFile starting at eof
end writeToFile