grepを使用してdivコンテンツを抽出する方法は?

Aug 24 2020

ファイル内の特定のdivコンテンツを抽出する必要があります。

内容は以下の通りです。

<div class="container">
    <div class="row">
        <div class="col-2">One of three columns</div>
        <div class="col-6">
            <p>One of three columns</p>
        </div>
        <div class="col-4">One of three columns</div>
    </div>
</div>

以下のコンテンツを抽出する必要があります。

<div class="col-6">
    <p>One of three columns</p>
</div>

私はこれをやろうとします。

cat test.html | tr -d '\n\t' | grep -o "<div class=\"col-6\">.*<\/div><div class=\"col-4\">"

次のように戻ります。

<div class="col-6"><p>One of three columns</p></div><div class="col-4">

コンテンツの前後の部分を削除するにはどうすればよいですか?

<div class="col-6">...</div><div class="col-4">

前もって感謝します!

回答

3 pLumo Aug 24 2020 at 15:16

使用する grep -A

$ grep -A 2 'class="col-6"' test.html | sed -n 2p
        <p>One of three columns</p>

差出人man grep

-A NUM--after-context=NUM
印刷NUMマッチングラインの後にコンテキストを後続の行を。

または使用awk

$ awk '/class="col-6"/{getline; print $0}' test.html
        <p>One of three columns</p>

注:これは、構造がテスト入力とまったく同じである場合にのみ機能します。一般的に、私は常に適切なxml / htmlパーサーを好みます。

例えばpythonさんbeautifulsoup

$ python3 -c '
from bs4 import BeautifulSoup
with open("test.html") as fp:
    soup = BeautifulSoup(fp)
print(soup.findAll("div", {"class":"col-6"})[0].findAll("p")[0])'
<p>One of three columns</p>

またはxmlstarletこのように使用します:

$ xmlstarlet sel -t -m '//div[@class="col-6"]' -c './p' -n test.html
<p>One of three columns</p>