gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:45:23 27 4
gpt4 key购买 nike

我有一个问题。我想使用 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>

脚本.sh

#!/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)

在该行下,我只需要值中的文本。没有html标签。但是我的脚本确实有效..

最佳答案

代码:

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

工作原理:

  1. $text被分配了一个未缩进的单行表示 test.html ;注意 :用作 sed 的定界符而不是 / ,因为任何字符都可以作为分隔符,而我们正在解析的文本具有 / -s 存在,所以我们不必用 \ 来逃避它们-s 在构建正则表达式时。
  2. $author假定介于 <p id="author" class="author"><br><a href="[^"]*"> 之间(其中 [^"]* 表示 «除 " 之外的任何字符,重复 N 次,N ∈ [0, +∞)»)以及接下来出现的任何标签。
  3. $quote假定介于 <div id="foo" class="foo"> 之间以及接下来的任何标签。
  4. 相当晦涩的结构<<<"$text"就是所谓的here-string , 这几乎等同于 echo "$text" |放在开头。

关于html - 使用 sed 或 grep 提取 HTML 标签之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44995218/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com