medrob
medrob

Reputation: 11

How to edit multiple files at once using applescript

I have an applescript I am able to use to edit the text in any file by replacing an instance of the text with different text.

Essential, this script should do these things in this order. Pick a folder. Pick out all the files with the .txt extension Reach each file individually and find specific text. Replace the text with new text. Close the file and move on to the next file.

The code is below

set aFolder to choose folder "Select folder to be processed"
tell application "Finder" to set allFIles to every file of aFolder whose name extension is in {"txt"}

repeat with someFile in allFIles

set SomeText to (read SomeFile) 

set {SearchText, ReplaceText} to {"Searches of this", "Replaces with this"} 
set {TempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, SearchText}
set {TextItems, AppleScript's text item delimiters} to {text items of SomeText, ReplaceText}
set {SomeText, AppleScript's text item delimiters} to {TextItems as text, TempTID}

set OpenFile to open for access SomeFile with write permission
try
    set eof of OpenFile to 0 
    write (text 1 thru -2 of SomeText) to OpenFile as text 
    close access OpenFile
on error errmess 
    log errmess
    try
        close access OpenFile
    end try
end try
end repeat 

I want to be able to either select multiple files at once or select a folder and use the script to edit all files within the folder that contain the searched text. Any help is appreciated.

EDIT: I know I can get the script to separate out the .txt files from the rest of the folder contents, and I know I can "see" these files (If I do a display dialog, for example, I can add a variable calling the name of SomeFile and see it in a dialog box) I just cannot read the file so I can edit it. What I need is to be able to open a folder, find all .txt files, open them, edit the text by replacing one instance of a specific word/phrase with another, and close the file before moving on to the next one.

Upvotes: 0

Views: 688

Answers (1)

pbell
pbell

Reputation: 3105

You can select folder and process all files in it with this script:

set aFolder to choose folder "Select folder to be processed"
tell application "Finder" to set allFIles to every file of aFolder whose name extension is in {"txt"}

repeat with someFile in allFIles
-- do here what you need for someFile (alias) !!
-- you can cut/paste your current script here
end repeat

Upvotes: 0

Related Questions