Move pdf files to variable folder based on variable in filename?

Hi All

I need some assistance with a script that i have cobbled together from various sources…

I need the script to-
Move pdf’s to a server volume to a unique folder that contains a unique job number in the filename.

Eg-
Find the job number in filename, e.g. - 007_12SF_OZ_105486.pdf.
Job number is always after “Z_” and before “.pdf” - 105486
Move files, based on this “job number”, to a network folder that contains the same job number
e.g. - J904 (105486_XX_XXXX)

The current script works until the last part, how do I make it move the pdf’s by choosing the job number after the “J904 (”?

Be aware the server auto generates a new J000 number for each folder.

Here is current script-

tell application "Finder"
	set the_files to every file of desktop
	repeat with this_file in the_files
		set the_name to name of this_file
		set job_number to items ((offset of "Z_" in the_name) + 2) thru -5 of the_name as string
		move this_file to folder ("Ed:Users:Ed:Desktop:Switch:Archive:" & job_number)
	end repeat
end tell

Thanks

Edit, found the right tags :smiley:

Hi, analogue. Welcome to MacScripter.

It’s probably not the fastest way to do the job if you have a lot of files, but I think this should get your script working:

tell application "Finder"
	set the_files to every file of desktop -- Assuming your desktop only contains relevant files!
	repeat with this_file in the_files
		set the_name to name of this_file
		set job_number to text ((offset of "Z_" in the_name) + 2) thru -5 of the_name
		move this_file to first folder of folder "Ed:Users:Ed:Desktop:Switch:Archive:" whose name contains ("(" & job_number & "_")
	end repeat
end tell

Thanks Nigel

Ok tried that, this is the error i get-
error “Finder got an error: Can’t get item 1 of {document file "005_12WW_NZ_102430.pdf" of desktop, document file "006_12WW_NZ_102430.pdf" of desktop}.” number -1728 from item 1 of {document file “005_12WW_NZ_102430.pdf” of desktop, document file “006_12WW_NZ_102430.pdf” of desktop}

Any ideas how to fix?

Also you mentioned this may not be the fasted way to do this, can you advise a better solution?

Thanks
Ed

I’m afraid not. You shouldn’t be getting that error with that code.

item 1 of {document file "005_12WW_NZ_102430.pdf" of desktop, document file "006_12WW_NZ_102430.pdf" of desktop} is the value of ‘this_file’ first time round the repeat. (It’s a reference to the list item, not just the direct reference to the file.) My only guesses are that either there’s something in your system preventing this reference from being understood inside the “Finder” ‘tell’ block (unlikely), or you’ve written extra code into the repeat to do something with the file after it’s been moved. In the latter case, the reference to it in its old location on the desktop might no longer be valid.