简单的 Grep 不匹配问题
我正在使用 Ubuntu 10.10 并使用 Grep 来处理一些 HTML 文件。
以下是 HTML 片段:
<a href="video.php?video=one-hd.mov"><img src="/1.jpg"><a href="video.php?video=normal.mov"><img src="/2.jpg"><a href="video.php?video=another-hd.mov">
我想提取 one-hd.mov
和 another-hd.mov
但忽略 normal.mov
。
这是我的代码:
example='<a href="video.php?video=one-hd.mov"><img src="/1.jpg"><a href="video.php?video=normal.mov"><img src="/2.jpg"><a href="video.php?video=another-hd.mov">'
echo $example | grep -Po '(?<=video.php\?video=).*?(?=-hd.mov">)'
结果是:
one
normal.mov"><img src="/2.jpg"><a href="video.php?video=another
但我想要
one
another
那里不匹配。
这是因为所谓的贪婪正则表达式吗?
我正在唱 GREP,但欢迎使用任何命令行 bash 工具来解决这个问题,例如 sed 等。
非常感谢。
I am using Ubuntu 10.10 and using Grep to process some HTML files.
Here is the HTML snippet:
<a href="video.php?video=one-hd.mov"><img src="/1.jpg"><a href="video.php?video=normal.mov"><img src="/2.jpg"><a href="video.php?video=another-hd.mov">
I would like to extract one-hd.mov
and another-hd.mov
but ignore normal.mov
.
Here is my code:
example='<a href="video.php?video=one-hd.mov"><img src="/1.jpg"><a href="video.php?video=normal.mov"><img src="/2.jpg"><a href="video.php?video=another-hd.mov">'
echo $example | grep -Po '(?<=video.php\?video=).*?(?=-hd.mov">)'
The result is:
one
normal.mov"><img src="/2.jpg"><a href="video.php?video=another
But I want
one
another
There is a mismatch there.
Is this because of the so-called Greedy Regular Expression?
I am sing GREP but any command line bash tools are welcome to solve this problem like sed etc.
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想使用 Perl 正则表达式进行 grep - 为什么不直接使用 perl?
将打印
You want use Perl regexes for grep - why not directly perl?
will print
这是使用 xmlstarlet 的解决方案:
Here is a solution using xmlstarlet:
使用 awk 的解决方案:
输出:
但我强烈建议您使用 html 解析器来代替,例如 BeautifulSoup
Solution using awk:
outputs:
But I strongly advice you to use a html-parser for this instead, something like BeautifulSoup