escape shell arguments in AppleScript?

I have the following command line works well in terminal

but I couldn’t escape quotes (have single quote and backslash in the above script) in applescript, this is what I tried, applescript didn’t give me error but I didn’t get my files renamed.


set renamer_command to "'s/\\d+/sprintf(\"%04d\",$&)/e'"
     do shell script "/opt/local/bin/rename " & quoted form of renamer_command & " ~/Downloads/test/*.pdf"

This is the output I get from Applescript

This is gives exactly what I want as seen in the output example.txt

set inString to "'s/\\d+/sprintf(\"%04d\",$&)/e'"
     do shell script "echo " & quoted form of inString & " > ~/Desktop/example.txt"

result

Again if I drop the output in my script and just look at the result in applescript then I get backslash in the result

set inString to "'s/\\d+/sprintf(\"%04d\",$&)/e'"
     do shell script "echo " & quoted form of inString

result

I worked a lot but I couldn’t get working script, please suggest me a solution, thanks

Hello.

When a string is quoted, then you don’t need to escape the escape character, as it is within a quoted string by single quotes, prohibiting the shell for interpreting/parsing it directly.

Otherwise, if your string is within double quotes, then you’d have to escape the escape character, so that $ for instance must be written as \$, if what you wanted was to print $, and not the literal $ then you would have to enter \\$ within double quotes, whereas $ would suffice within single quotes.

I have written a script that quotes a shell command-line for you, after you have copied the command line to the clipboard, the script can be found here.

This script should work if you are using an English system, or if you are using FastScripts, otherwise, run it from your editor, and adjust the text item delimiter, for extracting the text.

My understanding is that you are quoting twice the same string.

renamer_command
is the quoted form of “s/\d+/sprintf("%04d",$&)/e”

and you quoted it again in the do shell script instruction.

May you try with :

set renamer_command to "s/\\d+/sprintf(\"%04d\",$&)/e" # this time, it's not quoted here
do shell script "/opt/local/bin/rename " & quoted form of renamer_command & " ~/Downloads/test/*.pdf

or

set renamer_command to "'s/\\d+/sprintf(\"%04d\",$&)/e'"
do shell script "/opt/local/bin/rename " &  renamer_command & " ~/Downloads/test/*.pdf"

I can’t test because I found no rename UNIX command in my Startup disk.

KOENIG Yvan (VALLAURIS, France) lundi 16 septembre 2013 15:17:47

this work well, thanks