我有很多被我的艺术家误称的图片。我希望通过使用Automator避免给他更多的工作,但我是新手。现在他们按照what001a和what002a命名,但应该是what001a和what001b。所以基本上奇数编号为A,偶数编号为B.所以我需要一个脚本,将偶数编号改为B图像,并将它们重新编号为正确的顺序编号。我该怎么写这个剧本?
答案 0 :(得分:2)
AppleScript中嵌入的小型Ruby脚本提供了一个非常舒适的解决方案,允许您选择要在Finder中重命名的文件并显示信息成功或错误消息。
该算法按如下方式重命名文件:
number = first 3 digits in filename # e.g. "006"
letter = the letter following those digits # e.g. "a"
if number is even, change letter to its successor # e.g. "b"
number = (number + 1)/2 # 5 or 6 => 3
replace number and letter in filename
这就是:
-- ask for files
set filesToRename to choose file with prompt "Select the files to rename" with multiple selections allowed
-- prepare ruby command
set ruby_script to "ruby -e \"s=ARGV[0]; m=s.match(/(\\d{3})(\\w)/); n=m[1].to_i; a=m[2]; a.succ! if n.even?; r=sprintf('%03d',(n+1)/2)+a; puts s.sub(/\\d{3}\\w/,r);\" "
tell application "Finder"
-- process files, record errors
set counter to 0
set errors to {}
repeat with f in filesToRename
try
do shell script ruby_script & (f's name as text)
set f's name to result
set counter to counter + 1
on error
copy (f's name as text) to the end of errors
end try
end repeat
-- display report
set msg to (counter as text) & " files renamed successfully!\n"
if errors is not {} then
set AppleScript's text item delimiters to "\n"
set msg to msg & "The following files could NOT be renamed:\n" & (errors as text)
set AppleScript's text item delimiters to ""
end if
display dialog msg
end tell
请注意,当文件名包含空格时,将失败。
答案 1 :(得分:1)
我的一个朋友写了一个Python脚本来做我需要的事情。我想在这里发布它作为任何人在寻找帮助时遇到类似问题的答案。它是在Python中,所以如果有人想将它转换为AppleScript,那么可能需要它的那些。
import os
import re
import shutil
def toInt(str):
try:
return int(str)
except:
return 0
filePath = "./"
extension = "png"
dirList = os.listdir(filePath)
regx = re.compile("[0-9]+a")
for filename in dirList:
ext = filename[-len(extension):]
if(ext != extension): continue
rslts = regx.search(filename)
if(rslts == None): continue
pieces = regx.split(filename)
if(len(pieces) < 2): pieces.append("")
filenumber = toInt(rslts.group(0).rstrip("a"))
newFileNum = (filenumber + 1) / 2
fileChar = "b"
if(filenumber % 2): fileChar = "a"
newFileName = "%s%03d%s%s" % (pieces[0], newFileNum, fileChar, pieces[1])
shutil.move("%s%s" % (filePath, filename), "%s%s" % (filePath, newFileName))