Automatically move files to a parent folder + delete subfolder
I'm trying to figure out how to automatically move files from a folder to its parent folder and delete the original folder. To illustrate, here's my structure:
Parent Folder
– Subfolder
– File.avi
- File2.avi
- Otherfile.trash
I want to move my all my .avi files to the Parent Folder
and get rid of Subfolder
altogether (Subfolder
still won't be empty after moving these files, but I want to delete it and its leftover contents).
I've been playing around with Hazel but I guess my logic isn't the best and I can't figure it out. Is it possible with either Hazel or Automator or both?
Thanks in advance!
Solution 1:
The following solution will move all (and only) ".avi" files within subfolders (one level deep) to the parent folder and delete the subfolders. It may not be the most optimal solution since there are many different ways in which shell scripts can be written to solve a problem.
Assumptions and restrictions:
- Only ".avi" files will be moved. Other files will be ignored and deleted without warning.
- The (updated) script works only three levels below the parent folder. If there are subfolders within the subfolders containing ".avi" files, they will be deleted like any other file (including those ".avi" files).
- This script can handle ".avi" files that have spaces in the filename.
Caution: This uses a shell script that moves files and deletes directories/files completely. Have a backup before attempting to use it (even minor changes in the script can cause serious and irrecoverable issues). There is no way to recover from any issues except for restoring from a backup.
Solution:
- In Hazel, setup a watch for the parent folder in the Folders pane on the left.
- Add a rule by clicking the "+" button and name it as you wish.
-
Set the conditions criteria as follows
If <any> of the following conditions are met for <any of its sub-files or folders> <Any File>
-
Set the Do the following to the matched file or folder: as follows
<Run shell script> <embedded script>
- Click on the Edit script button next to the dropdown.
- Leave the Shell: option to the default (
'/bin/sh
). -
In the textbox below, copy and paste this shell script (I have included comments starting with # - they're just to make it easy to understand or modify)
# Get the directory name and go into it - this should be the parent directory dir=`dirname $1` cd $dir # Find all directories one level below # For each subdirectory, move all ".avi" files to its parent directory, # then remove the subdirectory and its contents (change avi to any other extension if necessary) find . ! -path . -type d -maxdepth 1 -exec sh -c ' dir="$0" mv $dir/*/*/*.avi $dir/.. rm -rf $dir ' {} ';'