Help with Sed and Applescript, replacing strings in files.

Discussion in 'Mac Programming' started by kidalex, May 23, 2009.

  1. macrumors newbie

    Joined:
    Sep 17, 2008
    Messages:
    18
    #1
    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:
    Code:
    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
    Code:
    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!
     
  2. macrumors member

    Joined:
    Aug 26, 2008
    Messages:
    36
    #2
    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

    Code:
    sed 's/xURIx/" & urlanswer & "/g'
    you can write

    Code:
    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.
     
  3. macrumors newbie

    Joined:
    Sep 17, 2008
    Messages:
    18
    #3
    Thank You

    Thank you so much, very easy to understand answer!

    :)
     

Share This Page