I have a simple AppleScript that calls a perl shell script to replace a string with another string (here one with two) in files with specified file extensions (here .txt and .xyz).
It used to work exactly as I have it below, but no longer does (possibly since updating to Mojave last year).
set CleanFiles to "
s/one/two/g;
"
set myFolder to choose folder with prompt "Choose a folder with files to be cleaned up:"
set theFolder to POSIX path of myFolder
do shell script "find " & theFolder & " \\( -name \\*.txt -o -name \\*.xyz \\) -print0 | xargs -0 perl -i -pe '" & CleanFiles & "'"
There is no error message, it seems to run but doesn't do anything.
What could be wrong?
Best Answer
The issue is that you need to quote file paths for unix, using the
quoted form of
command in AppleScript. In other words, line three should read:The problem happens because Mac variables can legally contain special characters — like spaces and single quotes — that the unix system uses. So, if you were to choose a folder named "My Test Folder", AppleScript would return its posix path as
/Users/username/My Test Folder
, but the command line invoked bydo shell script
would read that as three separate arguments, not one single file path. Thequoted form of
command quotes and escapes any unix special characters in the line of text so that they are not interpreted as special characters by the shell.