davidt
davidt

Reputation: 308

AppleScript: Move contents of folder in user defined amount to folders?

I'm fairly new at this and while having managed to created several basic scripts over the last few weeks I cannot seem to wrap my head around this one:

  1. Choose Folder (with say 1000 Files)
  2. Enter the number of Files per Folder (say 100)
  3. The script then creates 10 Folders (1000 Files / 100 in each folder)
  4. The script then moves the first 100 files sequentially into the the first folder - repeats till done.

The scripts I've put together for this process to this point are dismal, sloppy and outright pathetic so I dare not share them here.

My experiments have also resulted in the item listing causing issues with moving the files sequentially. instead of: ValOne_1.wav ValOne_2.wav ValOne_3.wav ValOne_4.wav ValOne_5.wav

I get: ValOne_1.wav ValOne_10.wav ValOne_100.wav ValOne_101.wav ValOne_102.wav

Thanks

Upvotes: 0

Views: 149

Answers (1)

regulus6633
regulus6633

Reputation: 19030

The Finder has a "sort" command so you can use that to avoid the numbering problem you mention. It seems to sort them the way you expect. So using that your workflow becomes easy with a little clever coding. Try the following. You only need to adjust the first 2 variables in the script to suit your needs and the rest of the script should just work.

set filesPerFolder to 3
set newFolderBaseName to "StorageFolder_"

set chosenFolder to (choose folder) as text

tell application "Finder"
    -- get the files from the chosen folder and sort them properly
    set theFiles to files of folder chosenFolder
    set sortedFilesList to sort theFiles by name

    set theCounter to 1
    repeat
        -- calculate the list of files to move
        -- also remove those files from the sortedFilesList
        if (count of sortedFilesList) is greater than filesPerFolder then
            set moveList to items 1 thru filesPerFolder of sortedFilesList
            set sortedFilesList to items (filesPerFolder + 1) thru end of sortedFilesList
        else
            set moveList to sortedFilesList
            set sortedFilesList to {}
        end if

        -- calculate the new folder information and make it
        set newFolderName to newFolderBaseName & theCounter as text
        set newFolderPath to chosenFolder & newFolderName
        if not (exists folder newFolderPath) then
            make new folder at folder chosenFolder with properties {name:newFolderName}
        end if

        -- move the moveList files
        move moveList to folder newFolderPath

        if sortedFilesList is {} then exit repeat
        set theCounter to theCounter + 1
    end repeat
end tell

Upvotes: 2

Related Questions