我有一大堆被我的艺术家错误命名的图像。我希望通过使用 Automator 来避免给他更多的工作,但我是新手。现在它们的命名顺序是 what001a 和 what002a,但应该是 what001a 和 what001b。所以基本上奇数编号是A,偶数编号是B。所以我需要一个脚本,将偶数编号更改为B图像并将它们全部重新编号为正确的顺序编号。我将如何编写该脚本?
问问题
748 次
2 回答
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
请注意,当文件名包含空格时,它将失败。
于 2012-04-18T19:03:37.920 回答
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))
于 2012-04-18T20:28:12.683 回答