[英]How can I extract title and list-item contents from HTML into a comma-separated list?
可悲的是我缺少正则表达式,尽管我正在阅读“精通正则表达式”并阅读了一些在线教程,但是却无所适从,所以希望有人能给我一个实际的例子来帮助我起步。
输入文件大致如下所示:
<html>
<head>
<title>My Title</title>
</head>
<body>
<p>Various random text...</p>
<ul>
<li>One</li>
<li><a href="example.com">Two</a></li>
<li>Three</li>
</ul>
<p>Various random text...</p>
</body>
</html>
我最终的目标是输出:
My Title,One,<a href="example.com">Two</a>,Three
例如,用逗号分隔带有标题的值和li标签的内容
但是,第一步是尝试删除标题之前和之后的所有内容,因此,当我决定使用sed时(我在Windows上运行了GNU sed 4.2版),我尝试如下操作:
弄清楚我需要匹配“一切”(包括换行符)到标题标签,并用什么代替,这意味着:
将每个字符都与一个点匹配,还要将换行符与/ n匹配,因此使该类成为一个并用*重复,这表示[。\\ n] *后跟标题标签,但不替换任何内容
所以
type file.html | sed "s/[.\n]*<title>//"
但这是行不通的,它只是删除字符串标题,而不删除前面的内容。
我要去哪里错了? 我想了解
任何建议表示赞赏。 提前致谢。
使用sed(以及tr和sed ...):
sed -n -e '/<title>\|<li>/{s/^[ ]*<[^>]*>//;s/<[^>]*>[ ]*$//p}' input | \
tr '\n' , | sed 's/,$/\n/'
使用单个sed表达式:
sed ':a;N;$!ba;s/\n//g; # loop, read-in all file, remove newlines
s/.*<title>//; # remove everything up to, including <title>
s/title>.*<ul>/title>/; # remove everything between </title> and <ul>
s!</ul>.*!!; # remove everything after </ul>, inclusive
s!</li>\|</title>!,!g; # substitute closing tags with commas
s/<li>//g; # remove <li> tags
s/,[ ]*$// # delete the trailing comma
' input
您可以通过多种方式来完成自己想做的事情,有些方式比其他方式更优雅。 这是一种使用单个Ruby单一代码获得预期结果的快捷方法。
ruby -ne 'BEGIN { output = "" }
output << $1 + ?, if %r{<(?:title|li)>(.*)</\1?}
END { puts output.sub(/,$/, "") }' /tmp/foo.html
该脚本将以原始问题中描述的格式打印结果。 例如,提供示例文本后,它会打印:
My Title,One,<a href="example.com">Two</a>,Three
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.