使用這個命令:
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) 個匹配節點。
有什么辦法嗎?不能只使用 simplehead或者tail因為我需要提取匹配的元素而不僅僅是一些 x 行。
uj5u.com熱心網友回復:
xmllint xpath可用于按位置請求標簽
xmllint --html --recover --xpath '//article[position()<=2]' tmp.html 2>/dev/null
uj5u.com熱心網友回復:
這可能對你有用(GNU sed):
sed -En '/<article/{:a;p;n;/<\/article>/!ba;p;x;s/^/x/;/x{2}/{x;q};x}' file
關閉隱式列印并打開擴展 regexp -En。
匹配和列印之間的行<article,<\article>然后在保持空間中增加一個計數器,如果出現次數完成則退出處理。
選擇:
cat <<\! | sed -Enf - file
/<article/{
:a
p
n
/<\/article>/!ba
p
x
s/^/x/
/x{2}/{
x
q
}
x
}
!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/350246.html
