让我们将您的问题分解为几个步骤。
首先,您要从查找器中检索文件。现在,假设您选择了一个文件夹并希望将脚本应用到其随附的文件中。
tell application "Finder"
set theFolder to the selection
set theFiles to every file of item 1 of theFolder
当你抓住 Finder 的选择时,你会得到一个列表,因此是第 1 项。这也让你有机会通过选择几个文件夹并使用重复循环来迭代它们来扩大它。
接下来,我们要遍历每个文件,所以让我们设置一个循环,调用一个函数并将我们正在查看的当前文件的文件名作为字符串传递给它:
repeat with aFile in theFiles
set originalName to the name of aFile
set newName to my threeDigitPrefix(originalName)
我们调用的子程序是一个非常简单的子程序,它首先将文件名字符串分开并将其存储在一个列表中:
set AppleScript's text item delimiters to " "
set splitName to (every text item of originalName) as list
然后我们将检查文件名是否以数字开头,如果不是,则退出函数。
try
first item of splitName as number
on error
return "FAILED" -- originalName does not start with a number
end try
现在我们将现有前缀分配给一个变量并检查它的长度以确定我们需要在文件名中添加多少个零:
set thePrefix to the first item of splitName
if the length of thePrefix is 1 then
set thePrefix to "00" & thePrefix
else if the length of thePrefix is 2 then
set thePrefix to "0" & thePrefix
end if
然后我们将前缀放回包含我们分解的文件名的列表中,然后重新组合它并将其返回给调用它的循环:
set the first item of splitName to thePrefix
return splitName as string
最后我们检查函数没有失败,并用我们刚刚从函数中得到的字符串重命名文件:
if newName is not "FAILED" then
set the name of aFile to newName
end if
我们完成了。把它们放在一起,你会得到这个:
tell application "Finder"
set theFolder to the selection
set theFiles to every file of item 1 of theFolder
repeat with aFile in theFiles
set originalName to the name of aFile
set newName to my threeDigitPrefix(originalName)
if newName is not "FAILED" then
set the name of aFile to newName
end if
end repeat
end tell
on threeDigitPrefix(originalName)
set AppleScript's text item delimiters to " "
set splitName to (every text item of originalName) as list
try
first item of splitName as number
on error
return "FAILED" -- originalName does not start with a number
end try
set thePrefix to the first item of splitName
if the length of thePrefix is 1 then
set thePrefix to "00" & thePrefix
else if the length of thePrefix is 2 then
set thePrefix to "0" & thePrefix
end if
set the first item of splitName to thePrefix
return splitName as string
end threeDigitPrefix