从原始名称中删除多个不同的后缀

时间:2019-04-10 03:46:28

标签: applescript

我有多个文件,这些文件的扩展名相同,但名称相同,但后缀可能不同。如何仅删除后缀?我打算为此使用AppleScript,因为它将通过Automator运行。

例如。 Apple_xh264_xdcamprofile123.mov Apple_mp4_prores321.mov Apple_xh265_prores456.mov

如何删除后缀,无论该文件名包含这些后缀,并且仅保留名称和扩展名。

预期结果。 Apple_xh264.mov Apple_mp4.mov Apple_xh265.mov

2 个答案:

答案 0 :(得分:0)

您可以从字符串的末尾(最后一次出现)查找分隔符,并使用偏移量来构建新名称:

set input to {"Apple_xh264_xdcamprofile123.mov", "Apple_mp4_prores321.mov", "Apple_xh265_prores456.mov"}
set output to {}

repeat with anItem in the input
  set reversed to (reverse of items of anItem as text) -- search from end
  if (offset of "_" in reversed) is 0 then -- suffix marker not found
    set end of output to anItem
  else
    set extension to text -1 thru -(offset of "." in reversed) of anItem
    set newName to text 1 thru -((offset of "_" in reversed) + 1) of anItem
    set end of the output to newName & extension
  end if
end repeat
return output

答案 1 :(得分:0)

另一个建议是使用Applescript文本项定界符。

您的字符串似乎始终是xxxx_yyyy_zzzz.eee(每组的长度无关紧要!)。

您可以使用文本项定界符“。”和“ _”,然后仅删除文本的第3部分(“ zzzz”)。这就是处理程序CleanName在下面的脚本中所做的事情:

set myList to {"Apple_xh264_xdcamprofile123.mov", "Apple_mp4_prores321.mov", "Apple_xh265_prores456.mov"}
set myOutput to {}
repeat with anItem in myList
    set newName to CleanedName(anItem)
    log newName
end repeat
return myOutput


on CleanedName(localOld) -- convert xxxx_yyyy_zzzz.eee into xxxx_yyyy.ee
    set AppleScript's text item delimiters to {".", "_"}
    try
        set localNew to (text item 1 of localOld) & "_" & (text item 2 of localOld) & "." & (text item 4 of localOld)
    on error
        set localNew to ""
    end try
    return localNew
end CleanedName

如果某些文件名未遵循预期格式,则使用Try块。 您可以在遍历所有文件的Automator循环中直接使用CleanedName