user1705731
user1705731

Reputation: 3

AppleScript, can't replace character in a text

I'm working on an AppleScript that is calling a Python script with the name of a file as an argument, something like :

set descriptionFiles to (every file of current_folder whose name extension is "txt")
repeat with textFile in descriptionFiles
   -- run a Python script that clears the xml tags and reformat the text of the file 
    do shell script "python3 '/Users/MBP/Documents/Python/cleanDescription.py' '" & textFile & "'"
end repeat

Now the AppleScript does fine as long as I'm not encountering a file with a single quote in it's name at which point it stops and throws an error.

To correct that, I've been trying to escape the single quote in the files name before passing it to the Python script but that's where I'm stuck. I'm using this routine :

on searchReplace(thisText, searchTerm, replacement)
    set AppleScript's text item delimiters to searchTerm
    set thisText to thisText's text items
    set AppleScript's text item delimiters to replacement
    set thisText to "" & thisText
    set AppleScript's text item delimiters to ""
    return thisText
end searchReplace

with a call like this :

tell application "Finder"
    set search_T to "'"
    set rep to "\\'"
    set selected to selection as alias
    set textName to selected as text
    set res to searchReplace(textName, search_T, rep)
end tell

Using the code above on a single file throws an error on the searchReplace(textName, search_T, rep) part, with a number of -1708

Any ideas ?

Upvotes: 0

Views: 503

Answers (1)

vadian
vadian

Reputation: 285082

The most reliable way to escape special characters in AppleScript is quoted form of. It handles all forms of quotation smoothly. Never do it yourself. It's also a good practice to quote paths always in do shell script lines even if they don't contain spaces.

Another issue is that textFile is supposed to be a POSIX path rather than a Finder specifier. And get the path to the python script once

set pythonScriptPath to POSIX path of (path to documents folder) & "Python/cleanDescription.py"
set descriptionFiles to (every file of current_folder whose name extension is "txt")
repeat with textFile in descriptionFiles
    -- run a Python script that clears the xml tags and reformat the text of the file 
    do shell script "python3" & space & quoted form of pythonScriptPath & space & quoted form of POSIX path of (textFile as text)
end repeat

Upvotes: 1

Related Questions