我有一个问题。我想使用 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'"
工作原理:
-
$text
被分配了一个未缩进的单行表示test.html
;注意:
用作sed
的定界符而不是/
,因为任何字符都可以作为分隔符,而我们正在解析的文本具有/
-s 存在,所以我们不必用\
来逃避它们-s 在构建正则表达式时。 -
$author
假定介于<p id="author" class="author"><br><a href="[^"]*">
之间(其中[^"]*
表示 «除"
之外的任何字符,重复 N 次,N ∈ [0, +∞)»)以及接下来出现的任何标签。 -
$quote
假定介于<div id="foo" class="foo">
之间以及接下来的任何标签。 - 相当晦涩的结构
<<<"$text"
就是所谓的here-string , 这几乎等同于echo "$text" |
放在开头。
关于html - 使用 sed 或 grep 提取 HTML 标签之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44995218/