PDA

View Full Version : Help with Sed and Applescript, replacing strings in files.




kidalex
May 23, 2009, 01:06 PM
Here's what I'm trying to do:

I have a text document with html code in it which is a template for social bookmarking things on the bottom of posts on my blog.

The author of this template has two variables, xTITLEx, and xURIx. Supposedly, you're supposed to find and replace them with Textedit/Notepad., but I want to be able to do this quickly, using applescript.

I have gotten this far:

set titlequestion to display dialog "What is the Title?" default answer "" buttons {"Cancel", "Go..."} default button 2
set titleanswer to text returned of titlequestion
do shell script "sed 's/xTITLEx/" & titleanswer & "/g' /Users/Alexh/Documents/Personal/code/Social.txt > /Users/Alexh/Documents/Personal/code/SocialNew.txt"
set urlquestion to display dialog "What is the URL?" default answer "" buttons {"Cancel", "Go..."} default button 2
set urlanswer to text returned of urlquestion
do shell script "sed 's/xURIx/" & urlanswer & "/g' /Users/Alexh/Documents/Personal/code/SocialNew.txt > /Users/Alexh/Documents/Personal/code/SocialNew1.txt"

It works fine until the url question/answer part. The problem is that the command sed 's/xURIx/urlanswer/g' file replaces the string xURIx in the file 'file' with the 'urlanswer', right? So I plugged in the variable from the question, urlquestion, and here's the problem: the url is formatted like this: http://google.com, and sed recognizes it as another command (whenever there's '/', it think's its an option). Please help me to make http://google.com not considered part of the command, but a string!

Thank you!



harry65
May 23, 2009, 01:17 PM
When using sed, you dont have to use '/' as the separator... you can use any character you want. I like to use @. So, instead of writing

sed 's/xURIx/" & urlanswer & "/g'

you can write

sed 's@xURIx@" & urlanswer & "@g'

(as long as 'urlanswer' does not contain an '@' character). I think this is much easier than trying to back-slash the '/' characters in urlanswer.

kidalex
May 23, 2009, 01:20 PM
Thank you so much, very easy to understand answer!

:)