简体   繁体   中英

Using backslashes in text replacement in AppleScript

I'm currently trying to create an AppleScript Application which will copy a folder from its "Contents" folder to the user's desktop. The code I have at the moment is:

set theFile to path to me as string
set hfsme to theFile & "Contents:Folder"
set posixPath to POSIX path of hfsme

set contentfolder to posixPath
set AppleScript's text item delimiters to " "
set textItem to text items of contentfolder
set AppleScript's text item delimiters to "\\ "
set contentfolder to textItem as string
set AppleScript's text item delimiters to {""}

do shell script "cp -a " & contentfolder & " $HOME/Desktop"

However, I receive the following error upon run:

"cp: /Users/myusername/Desktop/Test Application.app/Contents/Folder: No such file or directory"

I think this is because I expect the copy location to be:

/Users/myusername/Desktop/Test\ Application.app/Contents/Folder

But the script fails to add the backslash before the space which is what the shell command requires.

My question is: how do I replace the spaces in the variable with "\\ " ?

PS Before suggesting simply renaming the application a name which doesn't have a space, it is very important for me to have an application name with a space. I have also tried using "duplicate" command with AppleScript but wasn't able to get this to work but I am open to suggestions! (Please bear in mind that I'd like this script to work on other people's computers as well meaning that I cannot assume I already know the user's username.

Thank you in advance for any help!

Kind regards, Tom

Just add quoted form of , it handles the quotation in a very smart (and reliable) way.

set theFile to POSIX path of (path to me)
set contentfolder to theFile & "Contents/Folder"
do shell script "cp -a " & quoted form of contentfolder & " $HOME/Desktop"

If do shell script does not support $HOME write

do shell script "cp -a " & quoted form of contentfolder & space & quoted from of POSIX path of (path to desktop)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM