LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   sed question (https://www.linuxquestions.org/questions/programming-9/sed-question-317311/)

provkitir 04-26-2005 09:56 AM

sed question
 
hi
i'm tryin to use sed to substitute <td><a href="blah/blah"> with <td><a href="blah/blah2">, and this is for a whole bunch of files
so i do:
for i in *.html; do sed s/\<td\>\<a\ href=\"blah\/blah\"\>/\<td\>\<a\ href=\"blah\/blah2\"\> "$i"; done

and this does not work because of undetermined substitutes. i have no idea where i need the slashes and where i don't. please help!

thanks in advance.

LogicG8 04-26-2005 01:27 PM

A few things,

1) You need to quote your script for sed
sed -e 'your sed script here'

2) Quoting is messy but you just have to keep track of what program is looking at what data.
When you use quotes the shell will send the literal string inside. Therefore you don't need to
escape inside the quoted sed script except for things that sed needs escaped. Forget about the
rules for the shell. Angled brackets don't mean anything special to sed and so they don't need to be
escaped. '/' (forward slash) and '"' (double quote mark) need to be escaped

3) Assuming you want to replace multiple instances of that url you need to make your substitution
command global. You can do this by appending a g to your substitution command. sed -e 's/you/me/g'

4) You don't want to write over the file you are working on what happens is very implementation
defined and varies all over the place. Write your output to a temporary file and mv it to where you
want it to be

Example:
Code:

#/bin/sh

for FILE in `ls *.html` ; do
    TMPFILE=tmp.$RANDOM
    cat $FILE | sed -e 's/<td><a href=\"www.google.com\/blah\/blah\">/<td><a href=\"www.google.com\/blah\/blah2\">/g' >$TMPFILE
    mv $TMPFILE $FILE
done

The above script is brittle if you used a varied style of link declaration say <A HREF url> it
will break. It should get you going in the right direction.

provkitir 04-27-2005 04:29 PM

wow, thanks a lot! that really helped!

bigearsbilly 04-29-2005 05:39 AM

You could always put sed in a script file.
It often makes for an easier to read and reusable
tool.
Also a lot less worry about quotes and conflicts with the shell!


You also can use any delimiter other than '/', e.g '|'


Code:


#!/usr/bin/sed -f

/href/ {

    s|"blah/blah"|"blah/blah2"|g
}

this says: look for a href, if so do the following commnds on the line. (the sub)


sed is a wonderful tool ;)

provkitir 05-03-2005 09:41 AM

oh cool. i'll try that too, thanks!


All times are GMT -5. The time now is 01:23 AM.