Search code examples
automationapplescriptosx-mountain-lion

Applescript - move files to folders dependign on folders name


I need a generic script for Applescript which does the following: i have a bunch of files and folders in a folder. Folders are names lets say 10 11 12 125 126 Files have in the start of name folders name but then they have addon ie 10_XXX 11_XXX 125_XXX

Now after running a script id like files that have folders name to be moved to right folder. The file always has [foldername]_ but sometimes the files have [foldername]_ZZZ_ZZZ so only 1st of the _ is actually about folder.

Hope i am clear.

Script id liek to be generic [as working on the folder that i open in finder].

This script is really over my head.


Solution

  • I'd use a shell command like this:

    for f in *; do [[ -f $f ]] || continue; d=${f##*/}; echo mv "$f" "${d%%_*}"; done

    • [[ -f $f ]] tests if $f is a file
    • ${f##*/} removes the longest */ pattern from the start
    • ${d%%_*} removes the longest _* pattern from the end
    • Remove echo to actually move the files