Create a new text file with search & replaced text from another file

Basically I’ve been wanting to do something similar to this on the command line:

sed 's/apple-pie/apple_pie/g' file1.txt > file2.txt

I have a placeholder for the above’s “apple-pie” which is USERPATH but the text it will be replaced with (“apple_pie”) is a posix path. I can’t seem to get around the fact that sed’s delimiter for the search and replace text is the same as the path delimiter.

I have which doesn’t work:


on run
	set thePath to POSIX path of (path to me)
	set AppleScript's text item delimiters to "/"
	set parentFolder to ((text items 1 thru -3 of thePath) as string) & "/"
	set destination to POSIX path of (path to library folder from user domain) & "LaunchAgents/U6TV63RN87.com.yvs.MovieMakerAgent.plist"
	set source to parentFolder & "U6TV63RN87.com.yvs.MovieMakerAgent.plist"
	set theCommand to "sed 's/USERPATH/\"" & parentFolder & "\"/g' " & "\"" & source & "\" > \"" & destination & "\""
	do shell script theCommand
	log theCommand
end run

I have considered:


on run
	set thePath to POSIX path of (path to me)
	set AppleScript's text item delimiters to "/"
	set parentFolder to ((text items 1 thru -3 of thePath) as string) & "/"
	set destination to POSIX path of (path to library folder from user domain) & "LaunchAgents/U6TV63RN87.com.yvs.MovieMakerAgent.plist"
	set source to parentFolder & "U6TV63RN87.com.yvs.MovieMakerAgent.plist"
	set theCommand to "cp \"" & parentFolder & "U6TV63RN87.com.yvs.MovieMakerAgent.plist" & "\" \"Users/ktam/Library/LaunchAgents/U6TV63RN87.com.yvs.MovieMakerAgent.plist\""
	do shell script theCommand
	log theCommand
end run

And then doing the text replacement in place, but I’m not sure what the best way to do this is? Any help would be appreciated.

The content of the text file in question is:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>MachServices</key>
	<dict>
		<key>U6TV63RN87.com.yvs.MovieMakerAgent</key>
		<true/>
	</dict>
	<key>Label</key>
	<string>U6TV63RN87.com.yvs.MovieMakerAgent</string>
	<key>KeepAlive</key>
	<false/>
	<key>ProcessType</key>
	<string>Adaptive</string>
	<key>LimitLoadToSessionType</key>
	<string>Aqua</string>
	<key>ProgramArguments</key>
	<array>
		<string>USERPATH/U6TV63RN87.com.yvs.MovieMakerAgent.app/Contents/MacOS/U6TV63RN87.com.yvs.MovieMakerAgent</string>
	</array>
</dict>
</plist>

Hi.

You can either escape the slashes in the path or, more easily, just use a different delimiter in sed’s ‘s’ command. What ever comes after the ‘s’ (within reason) will be taken as the delimiter. Bars or colons or underscores are good alternatives, provided they’re not in the search or replace texts.

Thanks for the answer. I had no idea that sed’s delimiter changed based on the first character post the s.

My script now works.

Kevin