gpt4 book ai didi

shell - shell如何选择关键字范围内的内容?

转载 作者:行者123 更新时间:2023-12-04 16:16:47 26 4
gpt4 key购买 nike

这是一个包含大量 <section>... </section> 的 HTML 文件HTML 文件中的内容,其格式如下。

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<section>
<div>
<header><h2>This is a title (RfQVthHm)</h2></header>
More HTML codes...
</div>
</section>

<section>
<div>
<header><h2>This is a title (UaHaZWvm)</h2></header>
More HTML codes...
</div>
</section>

<section>
<div>
<header><h2>This is a title (vxzbXEGq)</h2></header>
More HTML codes...
</div>
</section>

</body>
</html>
我需要提取第二个 <section>...</section>内容。
这是预期的输出。
<section>
<div>
<header><h2>This is a title (UaHaZWvm)</h2></header>
More HTML codes...
</div>
</section>
我注意到我可以查找 UaHaZWvm第一个字符(和前面 2 行)直到我遇到下一个 </section> .
OP 的努力(在评论中提到): grep -o "hi.*bye" file这可以通过 awk 完成吗? , sedgrep请用工具?

最佳答案

因为您使用的是 HTML,所以要简单得多 and better使用可以识别格式的工具,例如 xmllint或其他一些允许您使用 XPath 表达式来提取部分文档的程序:

$ xmllint --html --xpath '//section[2]' input.html 2>/dev/null
<section>
<div>
<header><h2>This is a title (UaHaZWvm)</h2></header>
More HTML codes...
</div>
</section>
( xmllint 给出了很多关于标签的错误;我不认为它真的支持HTML5?无论如何,这就是为什么上面有标准错误的重定向。)

替代使用 hxselect 来自 W3C 的 HTML-XML-utils程序的集合。它使用 CSS 选择器来指定从文档中获取的内容,而不是 XPath:
hxselect 'section:nth-child(2)' < input.html

关于shell - shell如何选择关键字范围内的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66625250/

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