Search code examples
macosapplescriptfinder

AppleScript to read text file containing file names, search for each file name, and if a file is found copy it to a folder


Sorry to ask a question without even pasting my coding attempt, but I've never used AppleScript before and I have no idea how I would do this. I've found bits of code online that do small parts of each step of this, but some of the key parts I can't figure out how to do. If I can get this figured out it would save a lot of time. Basically my problem is that a client sent over thousands of photos, all in multiple levels of sub folders, along with an Excel document containing about 300 file names that I need to pull out and use. I can copy the file names from the Excel document into a plain text file, either multi-line or comma separated.

So this is what I need to do:

  • Open folder selector dialog to select the destination folder
  • Open file selector dialog to select the text file
  • Loop through each line (or comma separated value) of the text file
  • Take that string and search for a file name containing the string
  • Copy the first result into a folder (let's say Desktop:Found Photos)
  • If a file could not be found matching the string then add the search string into a text file (so I could email it to the client and ask them to send it to me)

If you can't code this whole process, if you could help me with looping through the text file, searching for the file name and copying the first result to another folder, and adding the file name to a text file if a file wasn't found, then I could probably piece it it all together. Thanks for any help.


Solution

  • You can try something along the lines of:

    set newFolder to POSIX path of (path to desktop as text) & "Found Photos"
    do shell script "mkdir -p " & quoted form of newFolder
    set filePaths to paragraphs of (read (choose file with prompt "Select file list") as «class utf8»)
    set fileFolder to POSIX path of (choose folder with prompt "Select folder containing files")
    
    set foundFiles to {}
    repeat with fileName in filePaths
        set fileName to (contents of fileName)
        set xxx to do shell script "find " & quoted form of fileFolder & " -name " & quoted form of fileName
        if xxx ≠ "" then
            tell application "System Events" to move file xxx to newFolder
            set end of foundFiles to fileName & return
        end if
    end repeat
    
    set foundFiles to (foundFiles as text)
    do shell script "echo " & quoted form of foundFiles & " > " & quoted form of POSIX path of ((path to desktop as text) & "FoundFiles.txt")