将两个(苹果脚本)脚本合并为一个



我正在尝试通过将以下两个Applescript合并为一个来简化我的工作流程,它们单独工作正常,但将它们组合起来会更有效。 简而言之,脚本 A 将文件名修剪为最后 3 个字符,脚本 B 将文件夹名称(文件所在的位置(添加到文件名中。 这可能是一个非常简单的修复,但我的脚本编写受到挑战,因此欢迎任何帮助。

脚本 A:

on open whichFile
repeat with aFile in whichFile
tell application "Finder"
set filename to name of aFile
set name of aFile to ((characters -1 thru -7 of filename) as string)
--set name of whichFile to ((characters 1 thru -4 of filename) as string) --trim last 3
end tell
end repeat
end open

脚本 B

on open theDroppedItems
repeat with a from 1 to length of theDroppedItems
set theCurrentDroppedItem to item a of theDroppedItems
set theCurrentDroppedItem to theCurrentDroppedItem as string
tell application "System Events"
set folderPath to theCurrentDroppedItem as string
--display dialog (folderPath)
set AppleScript's text item delimiters to ":"
set newFileName to (text item -4 of folderPath as string) & "-" & (text item -2 of folderPath as string) & "-" & (text item -1 of folderPath as string)
--display dialog (newFileName)
--rename file
set fileAlias to (theCurrentDroppedItem) as alias
set the name of fileAlias to newFileName
end tell
end repeat
end open

您可以从为组合脚本打开一个新的"脚本编辑器">文档开始。open处理程序将传递文件项列表,因此您可以添加一个新的处理程序声明,其中包含一个空的repeat语句,该语句将逐步执行已删除的项。 从那里,只需标识执行各种操作(trim name、get 文件夹名称等(的语句,并将它们复制到新open处理程序的repeat语句中,根据需要进行编辑以使用一致的变量名称。

运行新脚本后,您可以通过组合和/或重新排列可能在不同脚本中执行相同操作的语句来优化它。 将函数组织到它们自己的处理程序中也会很有帮助,例如下面的getNamePieces处理程序。 我还想添加一个带有choose file对话框的run处理程序,以便您可以进行测试,而无需将项目拖到快捷批处理上。

请注意,文件名包含任何扩展名,因此您应该将其分开,以便仅使用名称部分。 在获取文件夹名称的脚本中也有一些不必要的乱击,因此在清理它之后,您的脚本可能如下所示:

on run
open (choose file with multiple selections allowed)
end run
on open droppedItems
repeat with anItem in droppedItems
set {folderPath, theName, extension} to getNamePieces from anItem
set trimmedName to text -1 thru -3 of theName -- work with just the name part
tell application "System Events"
set folderName to name of disk item folderPath 
set newName to folderName & "-" & trimmedName & extension -- assemble the pieces
log newName -- for testing
# set name of anItem to newName -- uncomment to go live
end tell
end repeat
end open
to getNamePieces from someItem -- return the containing folder path, the name, and the extension
tell application "System Events" to tell disk item (someItem as text)
set theContainer to path of the container
set {theName, extension} to {name, name extension}
end tell
if extension is not "" then
set theName to text 1 thru -((count extension) + 2) of theName -- just the name part
set extension to "." & extension
end if
return {theContainer, theName, extension}
end getNamePieces

最新更新