Applescript - Replace character “Cant get every item of alias”

人盡茶涼 提交于 2019-12-12 23:23:53

问题


Below is my code to rename file. The code basically check for special character and replace with "_"(underscore).

Code

set thefile to choose file

    set Filename to my replace_chars(thefile, "   ", " ")
    set Filename to my replace_chars(thefile, "  ", " ")
    set Filename to my replace_chars(thefile, " ", "_")
    set Filename to my replace_chars(thefile, ",", "_")
    set Filename to my replace_chars(thefile, "!", "_")
    set Filename to my replace_chars(thefile, "~", "_")
    set Filename to my replace_chars(thefile, "*", "_")
    set Filename to my replace_chars(thefile, "/", "_")
    set Filename to my replace_chars(thefile, ":", "_")
    set Filename to my replace_chars(thefile, "(", "_")
    set Filename to my replace_chars(thefile, ")", "_")
    set Filename to my replace_chars(thefile, "___", "_")
    set Filename to my replace_chars(thefile, "__", "_")

tell application "Finder"

    set the name of file thefile to "Testing.png"
end tell

on replace_chars(this_text, search_string, replacement_string)
    set AppleScript's text item delimiters to the search_string
    set the item_list to every text item of this_text
    set AppleScript's text item delimiters to the replacement_string
    set this_text to the item_list as string
    set AppleScript's text item delimiters to ""
    return this_text
end replace_chars

It throws "Cant get every text item of alias" Please advice.


回答1:


choose file returns an alias. You can get the basename of the file with tell app "Finder" to name of:

set f to choose file
tell application "Finder" to set n to name of f
set n to replace(n, "a", "b")
tell application "Finder" to set name of f to n

on replace(input, x, y)
    set text item delimiters to x
    set ti to text items of input
    set text item delimiters to y
    ti as text
end replace

As far as I know, restoring text item delimiters property is not necessary if you don't rely on it later in the same script.



来源:https://stackoverflow.com/questions/18782688/applescript-replace-character-cant-get-every-item-of-alias

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!