使用 sed 或 grep 提取 HTML 标签之间的文本

raa*_*aah 5 html bash grep sed

我有个问题。我想使用 sed 或 grep 命令获取该 html 的两个部分的值。我怎样才能提取它们呢?

测试.html:

<html>
 <body>
  <div id="foo" class="foo">
   Some Text.
    <p id="author" class="author">
     <br>
     <a href="example.com">bar</a>
    </p>
  </div>
 </body>
</html>
Run Code Online (Sandbox Code Playgroud)

脚本文件

#!/bin/bash

author=$(sed 's/.*<p id="author" class="author"><br><a href="*">\(.*\)<\/a><\/p>.*/\1/p' test.html)
quote=$(sed 's/.*<div id="foo" class="foo">\(.*\)<\/div>.*/\1/p' test.html)
Run Code Online (Sandbox Code Playgroud)

在该行下我只想要值中的文本。没有 html 标签。但我的脚本不起作用..

hid*_*kgb 5

代码:

\n\n
text="$(sed \'s:^ *::g\' < test.html | tr -d \\\\n)"\nauthor=$(sed \'s:.*<p id="author" class="author"><br><a href="[^"]*">\\([^<]*\\)<.*:\\1:\' <<<"$text")\nquote=$(sed \'s:.*<div id="foo" class="foo">\\([^<]*\\)<.*:\\1:\' <<<"$text")\necho "\'$author\' \'$quote\'"\n
Run Code Online (Sandbox Code Playgroud)\n\n

怎么运行的:

\n\n
    \n
  1. $texttest.html被指定为;的无缩进单行表示形式。请注意,:被用作 的分隔符而sed不是/,因为任何字符都可以作为分隔符,并且我们正在解析的文本存在-s ,因此在构造正则表达式时/我们不必使用 -s 对其进行转义。\\
  2. \n
  3. $author假定位于<p id="author" class="author"><br><a href="[^"]*">(其中[^"]*表示除 \xc2\xabany 字符",重复 N 次,N \xe2\x88\x88 [0, +\xe2\x88\x9e)\xc2\xbb)和接下来的任何标记之间。
  4. \n
  5. $quote假定位于<div id="foo" class="foo">和 接下来的任何标签之间。
  6. \n
  7. 相当晦涩的构造<<<"$text"是所谓的here-string,它几乎相当于echo "$text" |放在开头。
  8. \n
\n