Flatten a folder's structure via AppleScript

May 12, '09 07:30:00AM

Contributed by: robclements

The following AppleScript traverses the currently-selected folder in the Finder, moves the contents of all subfolders of that folder up to the top level, then moves the (now empty) subfolders to the trash.

tell application "Finder"
  set theTopFolder to (selection as alias)
  --display dialog (theTopFolder as text)
  repeat with EachSubDir in (get every folder of folder theTopFolder)
      --display dialog (EachSubDir as text)
      repeat with Eachfile in (get every file of folder (EachSubDir as alias))
          move Eachfile to theTopFolder
        end try
      end repeat
      delete folder (EachSubDir as alias)
    end try
  end repeat
end tell
[robg adds: Copy and paste the above into Script Editor, then switch to the Finder, select a folder, switch back to Script Editor, and press Run. Because this script is non-reversible, I strongly recommend first using it on a non-critical test folder -- a duplicate of the folder you intend to flatten, for instance. That's how I tested it, and it worked as described (at least in 10.5; I don't know if it will run in 10.4). If this is something you do often, you could save the script to your user's Library » Scripts » Applications » Finder folder, where it'd be available from the Scripts entry in the menu bar.]

Comments (20)

Mac OS X Hints