AppleScript中的文件名增量

时间:2015-09-30 22:46:25

标签: file applescript increment automator

我正在使用一个轻量级自动机程序(applescript)来检测文件名,例如“file_v01”,“document_v03”,所有文件都以“_vXX”结尾递增(到“file_v02”,并且这里的内容很少令人惊讶。

我试图只是检测并删除文件名中的最后两个字符无效,任何想法都会很棒。不需要任何花哨的东西,只要_v02变成_v03。

任何帮助都会很棒!!

2 个答案:

答案 0 :(得分:1)

这是Automator AppleScript ,它会增加文件名中的最后两个字符

on run {input, parameters}
    tell application "System Events"
        repeat with thisFile in input
            set {tName, nameExt} to {name, name extension} of thisFile
            if nameExt is not "" then set nameExt to "." & nameExt
            set newName to my incrementNumber(tName, nameExt)
            if newName is not "" then -- the last two characters is a number
                set name of thisFile to newName
            end if
        end repeat
    end tell
    return input
end run

on incrementNumber(n, e) -- name and name extension
    set tBase to text 1 thru ((length of n) - (length of e)) of n -- get the name without extension
    try
        set thisNumber to (text -2 thru -1 of tBase) + 1 -- get the last two characters and increment
        if thisNumber < 10 then set thisNumber to "0" & thisNumber -- zero padding
        set tBase to text 1 thru -3 of tBase -- remove the last two characters
        return tBase & thisNumber & e -- the updated name (the basename without the last two characters + the number + the extension)
    end try
    return "" --  the last two characters is not a number
end incrementNumber

答案 1 :(得分:0)

这是您想要的脚本。

您需要先设置文件名和计数器之间的分隔符类型。然后,您需要定义计数器应该有多少位数。

我假设您的文件名中的计数器后面可能有一些文字(如文件扩展名!):

set Separator to "_v" -- separator between name and counter
set DigitsCount to 2 -- assuming only 2 digits for counter like 01, 02, ...99

set myName to "testxxx_v07_Copy.txt" -- example for the test

set PosSep to offset of Separator in myName
    if PosSep is 0 then
-- no separator, then no counter..do what's required !
else
set BaseName to text 1 thru (PosSep - 1) of myName
set myCount to (text from (PosSep + (length of Separator)) to (PosSep + (length of Separator) + DigitsCount - 1) of myName) as integer
set PostName to text from (PosSep + (length of Separator) + DigitsCount) to -1 of myName
end if
-- convert the counter to +1 in string with '0' before
set newCount to "00000" & (myCount + 1) as string
set newCount to text from ((length of newCount) - DigitsCount + 1) to -1 of newCount
set NextName to BaseName & Separator & newCount & PostName

-- BaseName now contains the basic name before the counter
-- newCount contains the new counter value (+1) as string formatted with x digits
-- PostName contains the current value of myName after the counter
-- NextName contains your new file name with new counter and extension if any