views:

238

answers:

4

I'm guessing this has to be an escaping issue, but I can't find it. What's most frustrating is that this is based on an old sed script I used that worked, so why can't I make it work when I try to re-use it a year later? ;)

Framework:

I have a file with a list of filenames in it that all need the same string of HTML searched and replaced.

I need to replace

 <a href="foo.html">Foo</a>

with

<a href="foo.html">Foo</a><a href="bar.html">Bar</a>

I was using:

#!/bin/bash
for i in $(cat sourcelist); do cat $i | sed 's,<a href="foo.html">Foo</a>,<a href="foo.html">Foo</a><a href="bar.html">Bar</a>,g'  > $i.bak ; mv $i.bak $i ; done
#end

But I'm getting the sed error "unterminated `s' command".

I've tried escaping the double quotes, the slashes, both, and still can't get it to parse.

It's late, and I'm losing focus. Any sharp eyes out there that can catch what I'm missing?

A: 

Have you tried escaping the quotation marks? e.g:

#!/bin/bash
for i in $(cat sourcelist); do cat $i | sed 's,<a href=\"foo.html\">Foo</a>,<a href=\"foo.html\">Foo</a><a href=\"bar.html\">Bar</a>,g'  > $i.bak ; mv $i.bak $i ; done
#end
Scanningcrew
you dont need to escape the double quotations in here
Amro
+2  A: 

Try not to use a for loop with cats like that due to space problems. Also, the cat to sed is useless.

while read -r line
do
    sed 's,<a href=\"foo.html\">Foo</a>,<a href=\"foo.html\">Foo</a><a href=\"bar.html\">Bar</a>,g' "${line}" > "${line}.bak"
    mv "${line}.bak" "${line}"
done < sourcelist

Of course, if you are using GNU sed, there is the -i option to create backups for you.

ghostdog74
A: 

Amro- I am running it as per the example aside from the strings 'foo Foo bar Bar' are different. I've triple checked for extra commas etc, and that version still errors for me :/

I tried the while loop in your example but that just overwrote the contents of all the files in 'sourcelist' to empty files. :(

Thanks for the suggestions.

NB
A: 

Fixed it by running Amro's while loop in a for:

#!/bin/bash

for i in $(cat sourcelist); do

while read  line
do
    sed 's,<a href=\"foo.html\">FOO</a>,<a href=\"foo.html\">FOO</a>
    <a href=\"bar.html\">Bar</a>,g'
        done < $i > $i.bak ; mv $i.bak $i ; done

May not be the most elegant, but it works.

Cheers.

NB
Why have you taken out two separate IDs?
Jonathan Leffler
First, it wasn't really my solution, I just added a fix. Second, we are assuming that the `sourcelist` file contains file names one per line. The reason for the while loop is to avoid the problem of spaces in file names. Your code above doesnt make sense to me?
Amro
sourcelist is one filename per line, you are correct Amro. Readline from the file didn't work as expected, so I thought I'd populate it as a variable to see if it worked which it did. I don't have the knowledge level to explain it, only to say that of all the examples given this one works. ;)
NB