【问题标题】:Match tag inside tag using bash使用bash匹配标签内的标签
【发布时间】:2021-12-20 18:14:22
【问题描述】:

我有这个 html

<article class="article column large-12 small-12 article--nyheter">
    <a class="article__link" href="/nyheter/14343208/">
            
        <div class="article__content">
            <h2 class="article__title t54 tm24">Person har falt ned bratt terreng - luftambulanse er på vei</h2>
        </div>
    </a>
    
</article>
<article class="article column large-6 small-6 article--nyheter">
    <a class="article__link" href="/nyheter/14341466/">
            <figure class="image image__responsive" style="padding-bottom:42.075%;">

<img class="image__img lazyload" itemprop="image" title="" alt="" src="data:image/gif;base64,R0lGODlhEAAJAIAAAP///wAAACH5BAEAAAAALAAAAAAQAAkAAAIKhI+py+0Po5yUFQA7" />

</figure>
        <div class="article__content">
            <h2 class="article__title t34 tm24">Vil styrke innsatsen mot vold i nære relasjoner</h2>
        </div>
    </a>
    
</article>

问题是我只想获取那些 html 标签,在本例中是文章标签,其中有一个子 img 标签。

我有这个 sed 命令

sed -n  '/<article class.*article--nyheter/,/<\/article>/p' onlyArticlesWithOutSpace.html > test.html

现在我想要实现的是只获取那些里面有 img 标签的文章标签。

我想要的输出是这样的

<article class="article column large-6 small-6 article--nyheter">
    <a class="article__link" href="/nyheter/14341466/">
            <figure class="image image__responsive" style="padding-bottom:42.075%;">

<img class="image__img lazyload" itemprop="image" title="" alt="" src="data:image/gif;base64,R0lGODlhEAAJAIAAAP///wAAACH5BAEAAAAALAAAAAAQAAkAAAIKhI+py+0Po5yUFQA7" />

我不能使用任何 xml/html 解析器。只是想使用 sed、grep、awk 等。

</figure>
        <div class="article__content">
            <h2 class="article__title t34 tm24">Vil styrke innsatsen mot vold i nære relasjoner</h2>
        </div>
    </a>

</article>

【问题讨论】:

  • I want to get only those html tags, in this case article tags, which has a child img tag inside them: sed 不是解决此问题的正确工具。在 perl, python or php 中使用 HTML 解析器。
  • 是的,我知道,但是就像我提到的那样,除了 sed、awk、grep 之外,我不能使用其他任何东西

标签: bash sed terminal grep


【解决方案1】:

小心:使用 解析 XML 是一个错误的好主意!

感谢Cyrus's comment 提供好的参考。

不管怎样,你可以试试这个:

sed -ne '/<article/{ :a; N; /<\/article/ ! ba ; /<img/p ; }'

【讨论】:

  • 得到这个错误 sed: 2: "/
  • @mohsinali1317:根据您的示例,没有错误。这正是您不使用sed 的原因。请Don't Parse XML/HTML With Regex.。我建议使用 XML/HTML 解析器(xmlstarlet、xmllint ...)。
  • @mohsinali1317 注意在脚本周围使用单个引号。这里使用 GNU sed
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-14
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 2016-08-21
  • 1970-01-01
相关资源
最近更新 更多