使用 bash 从 HTML 文件中只有 select n 个匹配行

only select n number of matched lines from HTML file using bash

使用这个命令:

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>

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

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

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

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

这可能适合您 (GNU sed):

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

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

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

选择:

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