Lionel
Lionel

Reputation: 3

Looking for an Applescript to find files and move them to different folder

I'm trying to find a script to find and move files to a different folder.

I've got a folder with hundreds pictures like this:

PA-600-01.jpg, PA-600-02.jpg, PA-600-03.jpg, PA-600-04.jpg, PA-601-01.jpg, PA-601-02.jpg, PA-601-03.jpg, PA-602-01.jpg, PA-602-02.jpg, PA-602-03.jpg, PA-602-04.jpg, PA-602-05.jpg

I want to move all the pictures with PA-600 (so PA-600-01.jpg, PA-600-02.jpg, PA-600-03.jpg and PA-600-04.jpg) on a folder (new or already existing, the easier...) named PA-600, move all the pictures with PA-601 (PA-601-01.jpg, PA-601-02.jpg and PA-601-03.jpg) on a folder named PA-601, move all the pictures with PA-602 (PA-602-01.jpg, PA-602-02.jpg, PA-602-03.jpg, PA-602-04.jpg and PA-602-05.jpg) on a folder named PA-602... until PA-699

I tried to move a file but not a group of files:

tell application "Finder" make new folder at alias "Macintosh HD:Users:AirYoSo:Desktop:600-699" with properties {name:"PA-600"} copy file "Macintosh HD:Users:AirYoSo:Desktop:600-699:PA-600-01.jpg" to folder "Macintosh HD:Users:AirYoSo:Desktop:600-699:PA-600" end tell

Upvotes: 0

Views: 3027

Answers (2)

adayzdone
adayzdone

Reputation: 11238

Try:

set myFolder to (choose folder)
set pFolder to POSIX path of myFolder
set folderNames to paragraphs of (do shell script "find " & quoted form of pFolder & " \\! -name \".*\" -type f -print0 | xargs -0 ls -t | grep -Eo PA-[0-9]{3} | uniq")

repeat with aFolder in folderNames
    (do shell script "mkdir -p " & quoted form of (pFolder & aFolder))
    tell application "System Events" to move (every file of myFolder whose name begins with aFolder) to (pFolder & aFolder)
end repeat

EDIT If you want to hard wire the path to the folder you can use:

set myFolder to "Macintosh HD:Users:YoSo:Desktop:test"
set pFolder to myFolder's POSIX path & "/"
set folderNames to paragraphs of (do shell script "find " & quoted form of pFolder & " \\! -name \".*\" -type f -print0 | xargs -0 ls -t | grep -Eo PA-[0-9]{3} | uniq")

repeat with aFolder in folderNames
    (do shell script "mkdir -p " & quoted form of (pFolder & aFolder))
    tell application "System Events" to move (every file of folder myFolder whose name begins with aFolder) to (pFolder & aFolder)
end repeat

Upvotes: 1

piokuc
piokuc

Reputation: 26164

No idea how to do it in applescript, but this is quite trivial to do in bash, which you have installed on your Mac:

#!/bin/bash
for (( c=600; c<=699; c++ ))
do
  echo "Processing PA-$c"
  mkdir -p PA-$c
  mv PA-$c-*.jpg PA-$c/
done

Save this to a file, for example script.sh, copy the file to the directory with your jpg files, and run it like this, in Terminal (replace /Users/lionel/files with the real path to your files):

$ cd /Users/lionel/files 
$ bash script.sh

Upvotes: 0

Related Questions