Find & replace text in a URL

I have a script that reads a URL in txt files and opens them in Safari (that’s run automatically by Hazel).

What I’d like it to do if possible is if the link contains then I’d like to replace it with so that it opens the normal desktop version rather than the mobile version on my Mac. Each txt file contains 1 URL, nothing else.

The script I use the get the URLs and open them is:

set theURL to read theFile

tell application “Safari”
open location theURL
end tell

Any help would be appreciated.


It makes it a bit easier to read if you use the applescript tags you see at the top of the edit box, anyways, the snippet below works for me. I don’t know how you run this thing, so I have commented out some error handling code, which you may want to use, or not, depending on your workflow.

set theFile to POSIX path of ((path to desktop as text) & "mytweet.txt")
# try
set theURL to read theFile
# on error 
# display dialog "Problem finding the file"
# error number -128
# end try

set {tids, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "mobile."}
# (hopefully you haven't any friends with the name mobile.)
set desktopURL to text items of theURL
set AppleScript's text item delimiters to tids
set theURL to desktopURL as text
tell application "Safari"	
	open location theURL
end tell

That works great. Thanks a lot for the help! :slight_smile:

.One more question.

If I wanted to add another instance to this script how would I do that? For example with this Amazon link I’d like to strip out “gp/” to open as the desktop version instead of the mobile version.


this is a different solution to handle multiple URL’s

property URLList : {{|URL|:"", cut:"mobile."}, {|URL|:"", cut:"/gp"}}

set theURL to ""

repeat with anURL in URLList
	if theURL begins with anURL's |URL| then
		set cutOffset to offset of anURL's cut in theURL
		tell theURL to set newURL to text 1 thru (cutOffset - 1) & text (cutOffset + (length of anURL's cut)) thru -1
		tell application "Safari"
			open location newURL
		end tell
		exit repeat
	end if
end repeat


Strangely it compiles fine in AppleScript Editor, but when I add it to Hazel (changing set theURL to “” to set theURL to read theFile) it says:

Expected “end” but found “property”.

Not sure if that’s a problem with Hazel or the script.