使用sed或grep在HTML标记之间提取文本
我有个问题。我想用sed或grep命令获得这个html的两个部分的值。我怎样才能把它们都提取出来 test.html:使用sed或grep在HTML标记之间提取文本,html,bash,sed,grep,xidel,Html,Bash,Sed,Grep,Xidel,我有个问题。我想用sed或grep命令获得这个html的两个部分的值。我怎样才能把它们都提取出来 test.html: <html> <body> <div id="foo" class="foo"> Some Text. <p id="author" class="author"> <br> <a href="example.com">bar</a> </p
<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>
一些文本。
script.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)
#/bin/bash
author=$(sed's/*
在该行下,我只需要值中的文本。没有html标记。
但是我的剧本没用 守则:
text=“$(sed's:^*::g'
,这几乎等同于放在开头的echo“$text”|
您可以使用解析html/xml文本并提取定义的xpath的值
以下是工作示例:
#!/bin/bash
author=$(xmllint --html --xpath '//div[@class="foo"]/text()' test.html | tr -d '\n' | sed -e "s/ //g")
quote=$(xmllint --html --xpath '//a/text()' test.html | sed -e "s/ //g")
echo "Author:'$author'"
echo "Quote:'$quote'"
- xpath定义需要从中提取文本的xml节点路径
- tr用于删除新行字符
- sed用于从提取的文本值中修剪字符串
您可以使用
我经常和curl一起使用
# curl -s http://www.example.com/ | html2text
# Example Domain
This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.
[More information...](https://www.iana.org/domains/example)
#
请使用专用的解析器,如:
使用html解析器,比如regex而不是regex,$author和$quote应该包含什么?我不能使用xmlstarlet。我没有sudo访问权限。@Cyrus author->“bar”和quote->“Some Text”。quote部分不起作用。它返回完整的文本string@meteor在您的问题中的test.html
上试用。它确实有效:
# cat test.html | html2text
Some Text.
[bar](example.com)
# curl -s http://www.example.com/ | html2text
# Example Domain
This domain is for use in illustrative examples in documents. You may use this
domain in literature without prior coordination or asking for permission.
[More information...](https://www.iana.org/domains/example)
#
$ xidel -s test.html -e '//p/a,//div/normalize-space(text())'
bar
Some Text.
$ eval $(xidel test.html -se 'author:=//p/a,quote:=//div/normalize-space(text())' --output-format=bash)
$ printf '%s\n' "$author" "$quote"
bar
Some Text.