jan
jan

Reputation: 259

AppleScript to replace text in multiple files

I'm trying to come up with a general multi-purpose way of replacing text in multiple files through AppleScript. This solution is using Perl. Is there maybe a more elegant way of doing this?

set myFolder to choose folder with prompt "Choose a folder:"
tell application "Finder"
    try 
        set txtFiles to (every file in entire contents of myFolder whose name ends with ".txt") as alias list
    on error 
        try
            set txtFiles to ((every file in entire contents of myFolder whose name ends with ".txt") as alias) as list
        on error 
            set txtFiles to {}
        end try
    end try
    set myFiles to txtFiles
end tell

repeat with CurrentFile in myFiles
    set CurrentFile to CurrentFile as string

    do shell script "perl -pi -e  's/replace/me/g; s/andme/too/g;' " & quoted form of (POSIX path of CurrentFile)

end repeat

Also, ideally, I'd like to make the Perl part a bit more readable, having each search/replace pattern on a separate line, but the do shell script in AppleScript seems to be unable to deal with line breaks, e.g.,

do shell script "perl -pi -e  '
s/replace/me/g; 
s/andme/too/g;
s/andhere/measwell/g;
' " & quoted form of (POSIX path of CurrentFile)

So essentially, is there a better/more elegant way of doing this? Doesn't necessarily have to be with perl, yet for a non-expert I continue to find perl the easiest way for handling this, especially as it's great at regexes (the solution should be able to do regexes).

Upvotes: 0

Views: 205

Answers (1)

ikegami
ikegami

Reputation: 385789

According to this, you could use

do shell script "perl -pi -e  '" & ¬
" s/replace/me/g;" & ¬
" s/andme/too/g;" & ¬
" s/andhere/measwell/g;" & ¬
"' " & quoted form of (POSIX path of CurrentFile)

Pardon my lack of knowledge of AppleScript, but maybe you can even do something like the following:

set PerlProg to "" & ¬
"s/replace/me/g; " & ¬
"s/andme/too/g; " & ¬
"s/andhere/measwell/g;"

set PerlCmd to "perl -i -pe'" & PerlProg & "'"

do shell script PerlCmd & " " & quoted form of (POSIX path of CurrentFile)

Upvotes: 2

Related Questions