用模式标记环绕徽标

时间:2013-10-11 19:00:50

标签: regex bash sed

我正在尝试替换:

   <td id="logo_divider"><a href="http://www.the-site.com"><img src=
   "/ART/logo.140.gif" width="140" height="84" alt="logo" border=
   "0" id="logo" name="logo" /></a></td>

使用:

   <td id="logo_divider"><span itemscope itemtype="http://schema.org/Organization"><a itemprop="url" href="http://www.the-site.com"><img itemprop="logo" src=
   "/ART/logo.140.gif" width="140" height="84" alt="logo" border=
   "0" id="logo" name="logo" /></a></span></td>

我写过的sed命令:

sed -E s#\(\<td id=\"logo_divider\"\>\)\(\<a \)\(href=\"http://www\.the-site\.com\"\>\<img \)\(src=\n\"/ART/logo\.140\.gif\".*?\n.*?\>\)#\1\<span itemscope itemtype=\"http://schema\.org/Organization\"\>\2itemprop=\"url\"\3itemprop=\"logo\"\4\</span\>\5#g default.ctp

有两个问题。第一个是命令失败:

sed: 1: "s#(<td": unterminated substitute pattern

第二个是,即使它成功,匹配也需要对换行符有效。更强大的解决方案将首先删除之间的任何换行符:

<td id="logo_divider">

</td>

然后针对已清理的文件执行替换。类似的东西:

sed -E s#\n##g | ...

1 个答案:

答案 0 :(得分:3)

正如chepner所说,使用正确的工具来完成正确的工作。

如果你有任何Python,我建议Beautiful Soup - 相对简单得到你想要的东西(这是粗鲁和粗暴的,但你得到的想法假设你在某些文件中有上述来源。 HTML):

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("./somefile.html"))

td = soup.find('td',id='logo_divider')
anchor = td.find('a')
anchor['itemprop'] = 'url'
span = soup.new_tag('span')
span['itemscope'] = True
span['itemtype'] = 'http://schema.org/Organization'
spanchild = anchor.replace_with(span)
span.append(spanchild)
相关问题