【问题标题】:only select n number of matched lines from HTML file using bash仅使用 bash 从 HTML 文件中选择 n 个匹配的行
【发布时间】:2021-12-19 20:37:31
【问题描述】:

使用这个命令:

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

我在我的 html 文档中获得了所有这些文章的标签。它们大约有 50 多篇文章。

示例输入:

<article class="article column large-12 small-12 article--nyheter">
    ... variable number of lines of dat
</article>

<article class="article column large-12 small-12 article--nyheter">
    ... variable number of lines of dat
</article>

<article class="article column large-12 small-12 article--nyheter">
    ... variable number of lines of dat
</article>

<article class="article column large-12 small-12 article--nyheter">
    ... variable number of lines of dat
</article>

我只想要 x 篇文章。就像前 2 篇文章一样。

输出:

<article class="article column large-12 small-12 article--nyheter">
    ... variable number of lines of dat
</article>

<article class="article column large-12 small-12 article--nyheter">
    ... variable number of lines of dat
</article>

这只是一个例子。我想要实现的是只选择 (x) 个匹配节点。

有什么办法吗?不能只使用简单的headtail,因为我需要提取匹配的元素而不仅仅是一些x 行。

【问题讨论】:

标签: html bash sed


【解决方案1】:

xmllint + xpath 可用于按位置请求标签

xmllint --html --recover --xpath '//article[position()<=2]' tmp.html 2>/dev/null

【讨论】:

  • 应该添加--html 选项。
  • 我收到很多这样的错误 HTML 解析器错误:htmlParseEntityRef: expecting ';'当我运行上述命令时
  • 添加了@Shawn 和--recover 建议的选项,该选项将尝试克服html 不一致。
  • 唯一的问题是文本编码错误。
  • 你有样品吗?
【解决方案2】:

这可能对你有用(GNU sed):

sed -En '/<article/{:a;p;n;/<\/article>/!ba;p;x;s/^/x/;/x{2}/{x;q};x}' file

关闭隐式打印并打开扩展正则表达式-En

匹配并打印&lt;article&lt;\article&gt; 之间的行,然后在保持空间中增加一个计数器,如果出现次数完成则退出处理。

替代方案:

cat <<\! | sed -Enf - file
/<article/{
:a
p
n
/<\/article>/!ba
p            
x
s/^/x/
/x{2}/{
x     
q     
}
x
}
!

【讨论】:

  • 我得到这个“/
  • @mohsinali1317 你在使用 GNU sed 并且还用单引号将命令括起来吗?
  • 不,我没有使用 GNU sed。
  • 你确定它必须是这种格式吗?
  • 我得到了这个 sed: -: 没有这样的文件或目录
猜你喜欢
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 2014-05-02
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-02
相关资源
最近更新 更多