简体   繁体   English

如何grep文件中的URL?

[英]How to grep for a URL in a file?

For example, I have a huge HTML file that contains img URL: http://ex.example.com/hIh39j+ud9wr4/Uusfh.jpeg 例如,我有一个包含img URL的巨大HTML文件: http//ex.example.com/hIh39j+ud9wr4/Uusfh.jpeg

I want to get this URL, assuming it's the only url in the entire file. 我想获取此URL,假设它是整个文件中唯一的 URL。

cat file.html | grep -o 'http://ex[a-zA-Z.-]*/[a-zA-Z.-]*/[a-zA-Z.,-]*'

This works only if the URL doesn't have the plus signs. 当URL没有加号时才有效

How do I make work for + signs as well? 我如何为+标志工作?

You missed the character class 0-9 (also useless use of cat) : 你错过了0-9级的角色(也没用过猫)

grep -o 'http://ex[a-zA-Z.-]*/[a-zA-Z0-9+-]*/[a-zA-Z0-9.,-+]*' file.html

Slight improvement, use -i for case insensitivity and only match images .jpg or .jpeg . 略有改进,使用-i表示不区分大小写,只匹配图像.jpg.jpeg

grep -io 'http://ex[a-z.-]*/[a-z0-9+-]*/[a-z0-9.,-+]*[.jpe?g]' file.html

Or how about just: 或者只是:

grep -io 'http://ex.example.*[.jpe?g]' file.html

The following fixes your regular expression for this specific case (including numbers and plus-signs): 以下修复了此特定情况的 正则表达式 (包括数字和加号):

http://ex[a-zA-Z.-]*/[a-zA-Z0-9.+-]*/[a-zA-Z0-9.+-]*

Demonstration: 示范:

echo "For example, I have a huge HTML file that contains img URL: http://ex.example.com/hIh39j+ud9wr4/Uusfh.jpeg"

I want to get this URL, assuming it's the only url in the entire file. 我想获取此URL,假设它是整个文件中唯一的URL。

cat file.html | grep -o 'http://ex[a-zA-Z.-]*/[a-zA-Z.-]*/[a-zA-Z.,-]*'

This works only if the URL doesn't have the plus signs. 仅当URL没有加号时才有效。 How do I make work for + signs as well? 我如何为+标志工作?

cat file.html| grep -o 'http://ex[a-zA-Z.-]*/[a-zA-Z0-9.+-]*/[a-zA-Z0-9.+-]*'

output: 输出:

http://ex.example.com/hIh39j+ud9wr4/Uusfh.jpeg

This does not extract all valid URLs. 不会提取所有有效的URL。 There are plenty of other answers on this site about URL matching. 关于URL匹配,这个网站还有很多其他答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM