Automatically move files into correct folder on server

applescriptautomatorterminal

I often need to move files from one location on a server into a set of hierarchical folders.

The filenames are usually 7 digits long – sometimes with some extra characters at the end.

The folders are set up as nested sets for each digit – 3 deep. So, a file named '6753687a.eps' for example would need be filed in the '675' folder, which is in the '67' folder, which is in the '6' folder, which is in the 'Images' folder at the root of the volume. There is no '6753' folder.

Ideally, I'd like to be able to drop groups of files into a folder or a droplet or something, and have the files automatically moved into their correct folders.

Does anyone know of a way to do this?

Best Answer

Automator Droplet

You can do this with an Automator workflow and a script (I'm using Python, but it could be done with Bash, Applescript or anything else really).

  1. Open up Automator, and choose Application type.
  2. Add a Run Shell Script action to the workflow.
  3. In the Run Shell Script action, set the Shell option to /usr/bin/python, and Pass input: to as arguments.
  4. Set the script text to the script as shown below. Be sure to change the destination path to your desired destination.
  5. Save the application to your desired location.

Script

import sys
import os
import subprocess

destinationPath = '/Users/rob/Desktop/test'

for f in sys.argv[1:]:
    name = os.path.basename(f)
    newdir = os.path.join(destinationPath, name[:1], name[:2], name[:3])
    print newdir

    if not os.path.exists(newdir):
        os.makedirs(newdir)

    subprocess.call(['mv', f, os.path.join(newdir,name)])
#eof

Important: Change the destinationPath = line to the path you want (i.e. the folder that contains your numbered folders). Make sure to retain the single quotes around the path.

Usage

Just drag and drop the files you want onto the application file you saved, and they'll be moved accordingly. If the proper folders don't exist already, they will be created.