Sunday, June 13, 2021
  • Index
  •  » Code Exchange
  •  » Removing Empty Folders from the Hierarchy of a selected Folder

#1 2021-06-09 12:50:15 pm

KniazidisR
Member
From:: Greece
Registered: 2019-03-03
Posts: 1878

Removing Empty Folders from the Hierarchy of a selected Folder

Such a simple task as removing empty subfolders from the hierarchy of a selected folder is difficult for many users (a very frequent request for help). Especially, this concerns the recursive removal of empty subfolders throughout the depth of the hierarchy. Therefore, I wrote the following script using Finder.

It doesn't pretend to be fast, but it works with visible structure elements (as I wanted). It allows selecting multiple root folders as well:

Applescript:


tell application "Finder" to set aFolders to (selection)
repeat with aFolder in aFolders
   my deleteEmptyFolders(aFolder)
   try
       tell application "Finder" to if count (items of aFolder) = 0 then delete (contents of aFolder)
   end try
end repeat


-- Direct recursion to remove empty subfolders.
on deleteEmptyFolders(aFolder)
   tell application "Finder" to set visibleItemsCount to count (items of aFolder)
   if visibleItemsCount = 0 then
       my deleteEmptyContainer(aFolder)
       try
           tell application "Finder" to delete (contents of aFolder)
       end try
   else
       tell application "Finder" to set aFolders to folders of aFolder
       repeat with aFolder in aFolders
           my deleteEmptyFolders(aFolder)
       end repeat
   end if
end deleteEmptyFolders


-- Reverse recursion to remove emptied containers.
on deleteEmptyContainer(aFolder)
   tell application "Finder"
       try
           set aFolder to container of aFolder
           set visibleItemsCount to count (items of aFolder)
           if visibleItemsCount = 1 then
               delete aFolder
               my deleteEmptyContainer(aFolder)
           end if
       end try
   end tell
end deleteEmptyContainer


Model: MacBook Pro
OS X: Catalina 10.15.4
Web Browser: Safari 14.1
Ram: 4 GB

Offline

 
  • Index
  •  » Code Exchange
  •  » Removing Empty Folders from the Hierarchy of a selected Folder

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)