用于更改文件名的 Applescript

Applescript for changing filenames

我想用 applescript 更改数千个文件名。

文件名都是这样写的:

第一部分 - 第二部分 XX.xxx

XX 为特定数字,.xxx 为 jpg 或 png 扩展名。

我想简单地改变周围的部分,这样它就会变成:

secondPart - firstPart XX.xxx

我想到了这个,但我的编码技能让我失望了。

tell application "Finder" to set aList to every file in folder "ImageRename"
set text item delimiters to {" - ", "."}
repeat with i from 1 to number of items in aList
    set aFile to (item i of aList)
    try
        set fileName to name of aFile
        set firstPart to text item 1 of fileName
        set secondPart to text item 2 of fileName
        set thirdPart to text item 3 of fileName
        set newName to secondPart & " - " & firstPart & "." & thirdPart
        set name of aFile to newName
    end try
end repeat

这只适用于第二部分的数字。 于是就变成了:

第二部分 XX - firstPart.xxx

如何将两个整数作为文本项分隔符?

一路上请帮帮我,教我:-)

只需使用space作为分隔符并构建部件。 编辑:在文本部分允许 spaces。

tell application "Finder" to set aList to every file in folder "ImageRename"
set AppleScript's text item delimiters to " "
repeat with i from 1 to number of items in aList
    set aFile to (item i of aList)
    try
        set fileName to name of aFile
        set lastParts to text item -1 of fileName
        set wordParts to (text items 1 thru -2 of fileName) as string
        set AppleScript's text item delimiters to " - "
        set newName to {text item 2 of wordParts, "-", text item 1 of wordParts, lastParts}
        set AppleScript's text item delimiters to " "
        set name of aFile to (newName as string)
    end try
end repeat
set AppleScript's text item delimiters to ""

要回答如何使用整数作为文本项分隔符的问题,只需:

set AppleScript's text item delimiters to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}

您可以一次设置多个文本项分隔符,但问题是当使用多个文本项分隔符时,您实际上并不知道两个文本项之间是什么。此外,在使用文本项定界符时,定界符在文本中的显示顺序并不重要。因此我建议改用正则表达式,您定义某种格式而不是分隔字符串并猜测哪个字符实际上是分隔符。

tell application "Finder" to set aList to every file in folder "ImageRename"
repeat with i from 1 to number of items in aList
   set aFile to item i of aList
   set fileName to name of aFile as string
   set newName to do shell script "perl -pe 's/^(.*) - (.*) ([0-9]{2}\.(jpeg|png))$/\2 - \1 \3/i' <<<" & quoted form of fileName
   if newName is not fileName then set name of aFile to newName
end repeat

我使用 perl 而不是 sed 的原因是因为 perl 确实支持替换中的 I 标志,这使得表达式的比较不区分大小写。

编辑(请求解释): 旧字符串的格式类似于:字符串可以以任何字符 (^.*) 开始,直到文字字符串“-”(-),然后再跟任何字符 (.*)。该字符串必须以 space 和 2 位数字 ([0-9]{2}) 开头的字符串结尾,后跟文字句点 (\.) 并以 jpeg 或 png ((jpeg|png )$).如果我们将所有这些放在一起,我们会得到一个正则表达式,如“^.* - .* [0-9]{2}\.(jpeg|png)$”。但我们想将匹配项分组到不同的部分,并 return 它们以与我们的新字符串不同的顺序排列。因此,我们通过放置括号将正则表达式分为 3 个不同的子匹配项:

^(.*) - (.*) ([0-9]{2}\.(jpeg|png))$

第一组匹配firstPart,第二组匹配secondPart,第三组(XX.xxx)匹配剩余部分。我们唯一需要做的就是在 return 新字符串时重新排序它们。新字符串中后跟数字的反斜杠将被匹配组替换。在替换命令中,这将被标记为 /s/search/\2 - \1 \3/flags.

我们替换的最后一部分是一些标志,我将 I 作为不区分大小写匹配的标志。

把这些放在一起让我

s/^(.*) - (.*) ([0-9]{2}\.(jpeg|png))$/ -  /I

注意:因为 \ 在 applescript 中是一个特殊字符,我们必须将 \ 写为 \\