Find and replace in text files using AppleScript -
i trying write applescript run via launch agent. script needs edit user preference plist file default save locations specific user. aware can done setting "~/documents" location in template plist. premier pro example needs write scratch files local drive. simplicity each user have these put in locations based on username. script need run if local profile has been created template @ first log on.
i have started using sample code found on site , making simple test below. test should edit txt file , replace 1 word another. script not working. when tested opens test.txt in textedit nothing more. no errors displayed either.
thank in advance
john.
replacetext("replace this", "replace this", "/volumes/usb_drive/test.txt") on replacetext(search_string, replacement_text, this_document) tell application "textedit" open this_document set applescript's text item delimiters search_string set this_text text of front document list set applescript's text item delimiters replacement_text set text of front document (this_text string) close this_document saving yes end tell end replacetext
here version doesn't need text edit. read file in utf-8 encoding, update it's contents , store file utf-8 encoded text. reason use try block around writing file there error if application has file open read permission @ same time. considering case block can wrapped around set ti every text item of thecontent if want search , replace case sensitive. there no need active when replace string, finding it.
set stringtofind "replace that" set stringtoreplace "with this" set thefile choose file set thecontent read thefile «class utf8» set {oldtid, applescript's text item delimiters} {applescript's text item delimiters, stringtofind} set ti every text item of thecontent set applescript's text item delimiters stringtoreplace set newcontent ti string set applescript's text item delimiters oldtid try set fd open access thefile write permission set eof of fd 0 write newcontent fd «class utf8» close access fd on error close access thefile end try
Comments
Post a Comment