问题
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