【问题标题】:Is there an AppleScript I can write to remove the first instance of a character in a file name?我可以编写一个 AppleScript 来删除文件名中字符的第一个实例吗?
【发布时间】:2019-12-28 08:59:48
【问题描述】:

在下图中,我正在尝试编辑 cat 目录中的每个文件名,使其仅包含一个“。”例如,对于所有其他文件名,我需要第一个文件名是 cat1.jpg 等等。

你们中的任何人都介意提供一些指导,告诉我如何实现 AppleScript(使用 Automator?)来重命名这个 cat 目录中的所有文件吗?

【问题讨论】:

  • 为什么不直接使用标准的重命名 Finder 功能?它可以替换名称中的文本,在您的情况下,替换“cat”。通过“猫”。此重命名功能在文件夹窗口的弹出菜单按钮中可用(屏幕副本工具栏右侧的第三个按钮)。
  • 不知道为什么我什至没有尝试在 Finder 中搜索替换所有功能!谢谢!成功了!

标签: macos terminal applescript automator


【解决方案1】:

假设您要重命名的所有文件都位于桌面上名为“Cat”的文件夹中

以下 AppleScript 代码将删除“.”的第一个实例...在它的位置留下一个空白空间。因此,“cat.1.jpg”将被重命名为“cat 1.jpg”等。

property theFolder : ((path to desktop) as text) & "Cat"
property originalFileName : missing value
property originalFileNameExtension : missing value

tell application "Finder" to set theFiles to (files of folder theFolder) as alias list

repeat with i from 1 to count of theFiles
    set thisItem to item i of theFiles
    tell application "System Events"
        set fileInfo to thisItem's properties
        set {originalFileName, originalFileNameExtension} to ¬
            {name of fileInfo, name extension of fileInfo}
    end tell

    set theOffset to offset of originalFileNameExtension in originalFileName
    set shortName to text 1 thru (theOffset - 2) of originalFileName

    set text item delimiters to "."
    set tempText to every text item of shortName
    set text item delimiters to " "
    set cleanedName to (tempText as text) & "." & originalFileNameExtension

    tell application "System Events" to set name of thisItem to cleanedName
end repeat

这将是您问题的完整 AppleScript 解决方案。但是,如果这对您来说只是一次性事件,那么通过 Finder 批量重命名文件将是一种更快的解决方案。

【讨论】:

    【解决方案2】:

    回答标题中的问题,一旦您在repeat 循环中循环遍历字符串,就可以从字符串中删除字符串的第一个实例:

    使用offset

    set s to "foo.bar.txt"
    set o to offset of "." in s
    set r to (text 1 thru (o - 1) of s) & (text (o + 1) thru -1 of s)
    

    使用Applescript's Text Item Delimiters

    set AppleScript's text item delimiters to "."
    set l to text items of s
    set r to (item 1 of l) & (text items 2 thru -1 of l as string)
    set AppleScript's text item delimiters to ""
    

    【讨论】:

    • 从 OP 的整个帖子来看,我认为可以肯定地假设他并不精通 AppleScript 代码。在我看来,在这种情况下,只需提及repeat loop 的使用并仅显示文本项分隔符的代码......提供了一个不完整的解决方案。为什么不提供repeat loop 的代码呢?此外,您的解决方案缺少实际更改文件名的代码。
    • wch,因为 SO 特别不应该是一个问题所在:我真的不知道编码,你能给我写一个可以为我做某事的脚本吗?如果结果是这样,这个问题应该被撤回。重点是鼓励他们做这项工作。没有显示任何代码的问题是可疑的,所以我让他们受益于回答唯一棘手的部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-16
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多