簡體   English   中英

如果,Automator / Applescript重命名文件

[英]Automator/Applescript rename files if

我有一大堆由我的藝術家命名的圖像。 我希望通過使用Automator避免給他更多的工作,但我是新手。 現在他們按照what001a和what002a命名,但應該是what001a和what001b。 所以基本上奇數編號為A,偶數編號為B.所以我需要一個腳本,將偶數編號改為B圖像,並將它們重新編號為正確的順序編號。 我該怎么寫這個劇本?

圖像列表

嵌入在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

請注意,當文件名包含空格失敗。

我的一個朋友寫了一個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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM