使用applescript,我可以在不修改(或获取)文件扩展名的情况下更改文件名吗?

时间:2012-12-25 16:12:05

标签: applescript filenames

我正在尝试更改文件的名称。看起来很简单,如果能够更改“显示的名称”属性。但我一直收到这个错误:

Can't set displayed name of alias "Path:to:file:" to "New_name"

这是我正在使用的文件夹操作脚本(即保存的AppleScript,然后使用文件夹操作设置服务将其分配给我的文件夹):

on adding folder items to this_folder after receiving these_items
    try
        repeat with this_item in these_items
            tell application "Finder" to set displayed name of this_item to "New_Name"
        end repeat

    on error error_message number error_number
        display dialog error_message buttons {"Cancel"} default button 1 giving up after 120
    end try
end adding folder items to

我发现的所有类似的东西(例如this question)首先获取“name”属性,然后剥离扩展名。我宁愿直接去“显示名称”属性。

2 个答案:

答案 0 :(得分:3)

如果文件的扩展名无法被Finder识别,或者显示所有扩展名已启用,则显示的名称可以包含扩展名。

追加上一个扩展名并不复杂:

tell application "Finder"
    set f to some file of desktop
    set name of f to "New_name" & "." & name extension of f
end tell

如果文件没有扩展名或者Finder无法识别扩展名,这也可以使用

set text item delimiters to "."
tell application "Finder"
    set f to some file of desktop
    set ti to text items of (get name of f)
    if number of ti is 1 then
        set name of f to "New_name"
    else
        set name of f to "New_name" & "." & item -1 of ti
    end if
end tell

如果您使用Automator创建了文件夹操作,则可以使用这样的do shell脚本操作:

for f in "$@"; do
    mv "$f" "New_name.${f##*.}"
done

答案 1 :(得分:1)

Lauir Ranta对 Finder 的回答是正确的。

但在发表评论后,我记得系统事件看起来比Finder更深入。

所以我交换命令将名称更改为 Finder 系统事件 所以现在它有效。

之前我有一个名为“someFile.kkl”的文件并且扩展程序刚刚编写完成。 Finder 将为扩展名返回“”并重命名该文件而不使用扩展名。 “了newName”

但当系统事件执行此操作时,它会看到扩展名并将名称设置为“newName.kkl”

tell application "Finder" to set thisFile to (item 1 of (get selection) as alias)


tell application "System Events"
    if name extension of thisFile is "" then

        set name of thisFile to "newName"
    else
        set name of thisFile to ("newName" & "." & name extension of thisFile)

    end if

end tell

设置文件夹操作。

on adding folder items to this_folder after receiving these_items
    try
        repeat with this_item in these_items
            tell application "System Events"
                if name extension of this_item is "" then

                    set name of this_item to "new_Name"
                else
                    set name of this_item to ("new_Name" & "." & name extension of this_item)

                end if

            end tell
        end repeat

    on error error_message number error_number
        display dialog error_message buttons {"Cancel"} default button 1 giving up after 120
    end try
end adding folder items to