Search code examples
stringreplaceapplescriptregistrylarge-files

Fast method to replace certain lines of large text file in Applescript


I have a large registry file (30,000+ lines) where I want to be able to change two lines using Applescript. The code that I currently have takes a few minutes to finish; I was hoping there was a way to cut this down to 2 seconds or less. Is there a way to do this?

The two lines are preceded by and formatted as such (I want to change the values of the Port and Address lines):

[path\that\always\stays\the\same] <# that isn't always the same>  
"Address"="<# that isn't always the same>"
"Port"="<# that isn't always the same>"

Here is my current code adapted from this thread at MacScripter

set theFile to (((theAppResourcesFolder) as text) & "system.reg") as alias
set N to open for access theFile with write permission
get eof N
if result > 0 then
    set theText to read N
    set eof N to 0
    write deleteLinesFromText(theText, "\"Address\"", "\"Port\"", finalResultAddress, finalResultPort) to N

    --close theFile
end if
close access N

Here is deleteLinesFromText:

on deleteLinesFromText(theText, deletePhrase1, deletePhrase2, newPhrase1, newPhrase2)
set newText to ""
try
    set textList to paragraphs of theText
    repeat with i from 1 to count of textList
        set thisLine to item i of textList
        if thisLine contains deletePhrase1 then
            set newText to newText & "\"Address\"=\"" & newPhrase1 & "\"" & return
        else if thisLine contains deletePhrase2 then
            set newText to newText & "\"Port\"=\"" & newPhrase2 & "\"" & return
        else
            set newText to newText & thisLine & return
        end if
    end repeat
    if newText is not "" then set newText to text 1 thru -2 of newText

end try
return newText
end deleteLinesFromText

Solution

  • Although sed will probably be quicker, this may shave some time off...

    set newText to ""
    set paraList to paragraphs of theText
    repeat with thisLine in my paraList
    
        if thisLine contains deletePhrase1 then
            set newText to newText & "\"Address\"=\"" & newPhrase1 & "\"" & return
        else if thisLine contains deletePhrase2 then
            set newText to newText & "\"Port\"=\"" & newPhrase2 & "\"" & return
        else
            set newText to newText & thisLine & return
        end if
    end repeat
    if newText is not "" then set newText to text 1 thru -2 of newText
    return newText