开发者

How do I fix this sed problem with unterminated lines?

开发者 https://www.devze.com 2022-12-10 14:08 出处:网络
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 se开发者_JAVA百科d script I used that worked, so why can\'t I make it wor

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 se开发者_JAVA百科d 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?


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号