Search code examples
variablespathapplescriptaliasfilenames

How to speed up Open Folder "whose name starts with" in AppleScript


Here's my basic AppleScript...

I have a fixed file path, followed by 1 variable folder, followed by a variable partial folder name (ie variable folder starts with "12345"). What I failed to work out is how to open the target folder in 1 instruction (because it's a variable). So I've had to open the enclosing folder, then do a "get folders whose name starts with". This is where my script is VERY slow. The target folder contains a couple of thousand folders, so searching for one that "starts with" isn't very practical.

set fixedFolderPath to ":Volumes:FixedFolder1:FixedFolder2:FixedFolder3:"
set varFolderName to "VariableFolder4:"
set finalFolderPath to fixedFolderPath & varFolderName

set partialName to "VariableNumber12345"

tell application "Finder"
    open finalFolderPath as alias
    set finalFolder to (get folders of front window whose name starts with partialName)
    set target of window 1 to finalFolder as alias
end tell

Solution

  • Pretty much anything will need to search the folder names, and there is some overhead from calling the application and the various Apple Events involved. A shell script (including its overhead) is usually more performant for stuff like this, even more so with an external volume that may not be indexed by Spotlight. POSIX paths can also be used directly without wrangling with the Finder.

    The following example uses find to perform a case insensitive search and return the first directory found:

    set fixedFolderPath to "/Volumes/FixedFolder1/FixedFolder2/FixedFolder3/"
    set varFolderName to "VariableFolder4/"
    set finalFolderPath to fixedFolderPath & varFolderName
    set partialName to "VariableNumber12345"
    
    set found to (do shell script "/usr/bin/find " & quoted form of finalFolderPath & " -type d -maxdepth 1 -iname " & quoted form of (partialName & "*") & " -print -quit") -- name pattern matches everything after partialName
    if found is not "" then
       tell application "Finder" to reveal found as POSIX file
    else
       (display alert "Directory not found" message "A folder name starting with " & quoted form of partialName & " was not found.")
    end if