我正在编写一个脚本,以获取名称格式为“名字姓氏 OL.pdf”的文件,将其复制并移动到新创建的“名字姓氏”文件夹,然后删除原始文件。我有人帮助我解决这个问题,但是当我尝试该脚本时,我不断收到错误“文件名'名字姓氏OL.pdf'与预期格式不匹配。根据我的理解,它不应该出错,但我可能会遗漏一些小东西,因为这是我第一次尝试编写脚本。任何帮助将不胜感激。
这是我尝试过的代码。
use AppleScript version "2.4" -- Yosemite (10.10) or later
use scripting additions
property cloud_folder : "/Users/will/Documents"
(* There are three ways of invoking this script:
- as a folder action (automated)
- by running the script directly (as an app, or within Script Editor
- by saving it as an app and dropping a file on it
*)
on adding folder items to theFolder after receiving theNewItems
-- Called after items have been added to a folder
--
-- theFolder is a reference to the modified folder
-- theNewItems is a list of references to the items added to the folder
repeat with each_file in theNewItems
my handle_file(each_file)
end repeat
end adding folder items to
on run
-- called if the script is run directly
-- prompt the user for a file to process
handle_file(choose file)
end run
on open of theFiles
-- Executed when files are dropped on the script
repeat with aFile in theFiles
handle_file(aFile)
end repeat
end open
on handle_file(theFile)
tell application "Finder"
set name_extension to name extension of theFile
-- check if we have a pdf file
if name_extension is "pdf" then
-- we at least have a PDF file
set filename to name of theFile
try
-- this assumes filename matches expectations ("first last OL.pdf")
-- any other formats throw an error and need additional logic handling
-- break out the filename into its components
set {oldTID, my text item delimiters} to {my text item delimiters, space}
set {first_name, last_name, OL} to text items 1 through 3 of filename
-- check to match the 'OL' string in the filename
if OL ≠ "OL" then error
on error
-- the file name does not match the expected format
display dialog "Filename '" & filename & "' does not match expected format" with icon stop buttons {"Cancel"} default button "Cancel"
end try
set my text item delimiters to oldTID
-- extract the applicant's name
set full_name to first_name & space & last_name as text
-- do we have an existing folder for this person?
if exists folder full_name of cloud_folder then
-- we do, so notify the user
display dialog "Folder for '" & full_name & "' already exists" with icon stop buttons {"Cancel"} default button "Cancel"
else
-- make a folder for the applicant
set new_folder to make new folder at folder cloud_folder with properties {name:full_name}
--and duplicate the file there
duplicate theFile to new_folder
-- optional: delete the original file: uncomment the next line
-- delete theFile
end if
end if
end tell
end handle_file
文件的 name 包含 名称扩展名,因此要仅使用不带扩展名的名称部分,您需要将其提取出来,例如:
set {fileName, name_extension} to {name, name extension} of theFile
if name_extension is not "" then set fileName to text 1 thru -((count name_extension) + 2) of fileName
另请注意,Finder 不了解 POSIX 路径,因此需要使用
POSIX file
进行强制。