Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Flatten a folder's structure via AppleScript Desktop
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. [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.]
    •    
  • Currently 2.10 / 5
  You rated: 3 / 5 (10 votes cast)
 
[12,695 views]  

Flatten a folder's structure via AppleScript | 20 comments | Create New Account
Click here to return to the 'Flatten a folder's structure via AppleScript' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Flatten a folder's structure via AppleScript
Authored by: abderrahman on May 12, '09 07:50:26AM

Doesn't work for me (on 10.5.6 with my Power G4 quicksilver 933 Mhz).



[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: joem on May 12, '09 08:07:23AM

Doesn't work for me either, on 10.5.6. When I was trying to run it from Script Editor, it was trying (and failing) to operate on files that were in the base folder and not in subfolders, thinking they were subfolders. Then, when I got rid of those files, it just said something about not being able to operate on {}. And when I ran it from the script menu, it simply did nothing, not even an error message.

It's a shame too, because I would really love something like this.



[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: robg on May 12, '09 09:04:29AM

Very weird -- I tested on 10.5.6 on my Mac Pro, and it ran fine. I just tested it again, using the text above copied and pasted into Script Editor on my MacBook Pro (also 10.5.6), and it seemed to work fine.

-rob.



[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: channui on May 12, '09 08:36:37AM
I've actually never had to do this, but I was curious to see what shell equivalent would be. Make sure you change into the top level of the directory hierarchy you want to flatten! These commands just print out what they would do. To make these actually work remove the word echo from the commands.
find . -not -type d -print0 | xargs -0J % echo mv -f % .
find . -type d -depth 1 -print0 | xargs -0 echo rm -rf
If you're using zsh as your shell, depending on your options, this may work for reasonably sized trees.
echo mv -f **/*(.) .
echo rm -rf *(/)


[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: Anonymous on May 12, '09 10:08:17AM
That's what I was thinking. Better still, use mv --backup in the first command. If a new file is copied with the same name as an existing file, the existing file will have a number appended to its name.

[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: PatrickS on May 12, '09 10:57:56AM
for i in *; do
    if [ -d "$i" ]; then
        mv "$i"/* "$i"/.??* ./
        rmdir "$i"
    fi
done


[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: robclements on May 12, '09 09:48:18PM

I tried the shell script thing extensively but it does not deal well with special characters in folder/file names. Parentheses, punctuation. slashes, etc all freak out a shell script [ at least my shell scripts]

---
-rob@robclements.com--



[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: PatrickS on May 14, '09 12:40:04PM

Hint 1: Put all variables containing filenames in "" when using them to reference a file/directory (resolves all practical issues)
Hint 2: See first find command mentioned above (and consult the man page to understand what's going on here)



[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: jbc on May 30, '09 08:11:03AM

Stumbled across this thread while researching a script for reorganizing some really unwieldy folder structures and 30,000 files, Thought I'd post back with my results in case it's useful to any one. I decided on a shell script version; it ended up being much faster than the Applescript versions I tried.

My basic goal was to flatten all files to the main folders, but for the larger folders (containing up to 4000 files) I wanted to sort the files into alphabetical subfolders. I decided on running the script as a contextual menu item using OnMyCommand, so all selected folders in the Finder are passed to the script one at a time. So if you're using Applescript or Platypus to set up a droppable app or whatever you'll need to set up the folder handling.

Note that I used a Macports-installed version of GNU mv (gmv) for moving files, since the default mv on my Tiger setup doesn't support the "--backup" option. The script moves any duplicates found to a folder named "Duplicate". Also any invisible dot files (like .DS_store) in the main folder should be preserved; any in subfolders will be deleted.

cd __OBJ_PATH__
## ^^^^^^^^^^^^ change pwd to selected folder - specific to OnMyCommand usage!

## Flatten files to selected folder, tagging duplicates
find . -mindepth 2 -type f -not -name ".*" -print0 | xargs -0J % gmv --backup=numbered % .
find . -mindepth 1 -type d -print0 | xargs -0 rm -rf

## If duplicate files were tagged, store in new folder "Duplicate"
FILES=`find . -type f -regex ".*\.[\~0-9]*"`
if [[ $FILES ]]; then
	mkdir ./Duplicate
	echo "$FILES" | tr "\n" "\0" | xargs -0J % gmv % ./Duplicate
fi

## If over 500 files, sort files into new alphabetical folders based on first character of filename
declare -i FILECOUNT=`find . -type f -not -name ".*" | wc -l`
if [[ $FILECOUNT -ge 500 ]]; then
	for CHAR in A B C D E F G H I J K L M N O P Q R S T U V W X Y Z; do
		FILES=`find . -maxdepth 1 -type f -iname $CHAR"*"`
		if [[ $FILES ]]; then
			mkdir ./$CHAR
			echo "$FILES" | tr "\n" "\0" | xargs -0J % gmv % ./$CHAR
		fi
	done

## Sort any remaining files into new "0-9" folder
	FILES=`find . -maxdepth 1 -type f -not -name ".*"`
	if [[ $FILES ]]; then
		mkdir ./0-9
		echo "$FILES" | tr "\n" "\0" | xargs -0J % gmv % ./0-9
	fi
fi


[ Reply to This | # ]
Two BIG potential problems
Authored by: AndrewTurner on May 12, '09 09:06:52AM
I decided to test with the following structure
Test Folder
  file1
  Inner folder
    file1
    file2
    Innermost folder
      file1
      file2
      file3
The different files had different contents even if they had the same names. The result:
Test folder
  file1 (from Test folder)
  file2 (from Inner folder)
and in the trash:
Inner folder
  file1 (from Inner folder)
  Innermost folder
    file1 (from Innermost folder)
    file2 (from Innermost folder)
    file3 (from Innermost folder)
So, the script doesn't deal well with duplicate file names and any nested folders will get dumped in the trash with all their contents. If you know what's in your folders and know that neither of these issues are a problem for you, the script will work as written, just remember to select the top level folder before you start.

[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: ChaChi on May 12, '09 10:20:19AM
Here's a script I just made out of curiosity. It works for me here on 10.5.6:
--START
--GET FINDER SELECTION
tell application "Finder"
	activate
	set selectedFolder to selection as alias
end tell

--TEMPORARILY RENAME TOP LEVEL FOLDERS TO PREVENT FILE NAME CONFLICTS
set posixFolderPath to text 1 through -2 of (POSIX path of selectedFolder)
set folderList to paragraphs of (do shell script "find " & quoted form of posixFolderPath & " -type d -depth 1")
repeat with aFolder in folderList
	set theFolder to aFolder as string
	do shell script "mv " & quoted form of theFolder & " " & quoted form of (theFolder & "-FOLDERTMP")
end repeat

--LIST ALL FILES
set fileList to paragraphs of (do shell script "find " & quoted form of posixFolderPath & " -not -name '.DS_Store' -not -type d")

repeat with aFile in fileList
	set nameList to list folder POSIX file posixFolderPath
	
	set theFile to aFile as string
	set theInfo to info for (POSIX file theFile)
	set theName to name of theInfo
	
	--RENAME FILE IF NAME ALREADY EXISTS
	if theName is not in nameList then
		set newName to theName
	else
		set theExt to name extension of theInfo
		if theExt is not missing value then
			set theExt to "." & theExt
		else
			set theExt to ""
		end if
		set theName to text 1 through -((count of theExt) + 2) of theName
		set x to 0
		repeat
			set x to x + 1
			set newName to theName & "-" & x & theExt
			if newName is not in nameList then exit repeat
		end repeat
	end if
	
	--MOVE FILE TO TOP LEVEL DIRECTORY
	do shell script "mv " & quoted form of theFile & " " & quoted form of (posixFolderPath & "/" & newName)
end repeat

--DELETE ALL FOLDERS
do shell script "find " & quoted form of posixFolderPath & " -type d -mindepth 1 -delete"
--END


[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: abderrahman on May 12, '09 02:39:34PM

Yes! This works, for me. And on 10.5.7, just now installed.



[ Reply to This | # ]
My GUI method
Authored by: MJCube on May 12, '09 09:12:28PM

I do this periodically with the files iChat saves in daily sub-folders, to collect them in monthly folders instead. When I've accumulated a bunch of folders, I:

1. Select them all
2. View as List, sorted by Name
3. Hit right-arrow to open all their triangles at once
4. Command-drag over everything from bottom to top, letting the window auto-scroll if necessary. This reverses my selection, selecting the files and deselecting the folders all in one motion.
5. Drag the files to the destination folder all at once
6. Trash the empty sub-folders

This works because the sub-folders are contiguous in alphabetical order; it wouldn't be as convenient otherwise. And unlike the script in the hint, this works on any subset of sub-folders I select; it doesn't have to be all of them.



[ Reply to This | # ]
My GUI method
Authored by: ragmaxone on May 13, '09 11:28:35AM

doesn't work with duplicate folders and only for the direct subfolders...

but I like the work around!



[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: robclements on May 12, '09 09:43:05PM

This can also be accessed via Automator from a right-click in the finder.

---
-rob@robclements.com--



[ Reply to This | # ]
a bit simpler...
Authored by: tedw on May 13, '09 11:16:26PM
really, all you need to flatten a folder entirely is the following code:
tell application "Finder"
	set theFiles to a reference to every file of (entire contents of folder "old:folder:path")
	duplicate theFiles to folder "new:folder:path"
end tell
This will make a list of references to all the files on all levels of the folder, and then duplicate them into the new folder. duplicate names in the folder hierarchy will be enumerated in classic Mac style (in Andrew's example above I ended up with file1, file1 2, file1 3, file2, file2 2, file3). you could use move instead of duplicate, but that will throw an error for duplicate file names.

[ Reply to This | # ]
a bit simpler...
Authored by: ragmaxone on May 23, '09 12:37:23AM

A bit?
I made a script that does the same, without the "entire contents" thing... it's about 80 lines of code :'(

Thanks for this hint!



[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: slferris on May 27, '09 07:26:11PM

Is there any way to make this script so it works in Path Finder? i.e., other than changing the tell application command from Finder to Path Finder, which doesn't seem to work for me.



[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: tedw on May 27, '09 10:11:51PM

which script? Path Finder uses different labels for objects than the Finder (check out its applescript dictionary) and not all of the Finder's commands, classes and properties are implemented. you could do it, maybe, but it would take some translating and finagling to make it work.



[ Reply to This | # ]
Flatten a folder's structure via AppleScript
Authored by: wstrigel on May 09, '13 10:10:08PM

Works like a charm. It's scary at first when you hear all the files popping up and then the folders going to the trash. But it's the easiest instruction I found. Thanks!



[ Reply to This | # ]