开发者

AppleScript to find & replace sets of string in a selected file

I want to use AppleScript to find and replace text in a chosen document. The text I want to replace will always be the same, so I want to set some predefined variables with that string, search the chosen document for that string, and replace it with another predefined string. I want to repeat this find and replace process about 4 times (looking for different string variables each time) for that one document. Once this is done I want to automatically save the modified document.

can someone provide me with simple script to do this? this is that I have so far...

tell application "Finder"
    set theFile to (open for access (choose file with prompt "Select a file to read:"))
    set txt to (read theFile for (get theFile))
end tell

on replaceText(find, replace, subject)
set prevTIDs to text item delimiters of AppleScrip开发者_Python百科t
set text item delimiters of AppleScript to find
set subject to text items of subject

set text item delimiters of AppleScript to replace
set subject to "" & subject
set text item delimiters of AppleScript to prevTIDs

return subject
end replaceText

get replaceText("lorem", "ipsum", txt)

the problem is it is not reading all the content of the file (.html). of a lorem ipsum paragraph it is only reading "ipsum ipsum dolor sit amet, consectetur adipisicing elit, sed do eius" i tried using eof in the (get theFile) but that doesnt work either


Yup. :)

set the search_document to (choose file of type "TEXT")
replaceText("whatever you want to search for", "whatever you want to replace with", search_document)

on replaceText(search_string, replacement_text, this_document)
    tell application "TextEdit"
        open this_document
        set AppleScript's text item delimiters to the search_string
        set this_text to the text of the front document as list
        set AppleScript's text item delimiters to the replacement_text
        set the text of the front document to (this_text as string)
        close this_document saving yes
    end tell
end replaceText

A quick warning about this script, though. If you were to replace every occurence of the word one with the word two in a document containing this string...

If someone added one plus one, what would be the result?

...this would be your result...

If sometwo added two plus two, what would be the result?

Other than that, there isn't anything to worry about.

Happy coding! :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜