AppleScript to massage URLs I want to have a Services menu item that takes the selected text (a URL) and escapes the percent character and the # character:


Replace % with \%
Replace # with \string#


I copied and edited an exisiting script that does similar text manipulation.  This seems to work fine except when the URL contains a &amp;.

I think this has something to do with needing to use quoted form of string, but I can't quite determine the correct place to specify that.

Sample Input: 

http://books.google.com?xxx&amp;xxx%22+xxx#v=onepage&amp;q=%22Search%20String&amp;f=false


Required Output

http://books.google.com?xxx&amp;xxx\%22+xxx\string#v=onepage&amp;q=\%22Search\%20String&amp;f=false


Code:

on run {input, parameters}
set sanatizedURLString to ¬
    (do shell script ("echo " &amp; input &amp; "  | sed 's/%/\\\\%/g' | sed 's/#/\\\\string#/g' ;"))
return sanatizedURLString
end run
This is how I'd code it:

on run {input, parameters}
    set aURL to input as string
    set sanatizedURL to ¬
        do shell script "sed -e 's:%:\\\\%:g' -e 's:#:\\\\string#:g' &lt;&lt;&lt; " &amp; aURL's quoted form 
    return sanatizedURL
end run


&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hint: Mouse over and horizontal scroll to see full code.



Notes:

input is a list e.g.:

{"http://books.google.com?xxx&amp;xxx%22+xxx#v=onepage&amp;q=%22Search%20String&amp;f=false"}


set aURL to input as string makes it:

http://books.google.com?xxx&amp;xxx%22+xxx#v=onepage&amp;q=%22Search%20String&amp;f=false


In the do shell script command sed only needs to be called once, not twice as in the original code. sed can take multiple commands by using the -e option, thus no need in this case to pipe the output of one sed command to another sed command.

It is not necessary to echo something to sed as it can process a file or a here string, thus the use of &lt;&lt;&lt; in the do shell script command, followed by &amp; aURL's quoted form which is e.g.:

'http://books.google.com?xxx&amp;xxx%22+xxx#v=onepage&amp;q=%22Search%20String&amp;f=false'


By quoting the value of aURL it keeps the shell from processing any shell special characters in the string.

Thus, when run, the do shell script command looks like e.g.:

do shell script "sed -e 's:%:\\\\%:g' -e 's:#:\\\\string#:g' &lt;&lt;&lt; 'http://books.google.com?xxx&amp;xxx%22+xxx#v=onepage&amp;q=%22Search%20String&amp;f=false'"


&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hint: Mouse over and horizontal scroll to see full code.

The use of : vs. / in the sed command is a personal preference in this case as it makes the command easier to read when having to make multiple escapes.

The use of echo in the original code flattens the list to a string, however I prefer to not use that method in order to make the do shell script command less complicated.