提取域名正则表达式

echo "http://domain/test" | grep -Eo "(https?://)[^/]+([[^:blank/]]*)"
效果如下:

[root@ ~]# echo "http://domain/test" | grep -Eo "(https?://)[^/]+([[^:blank/]]*)"
http://domain/

提取域名及端口号

echo "http://domain:8080/test" | grep -Eo "(https?://)[^/]+"
效果如下:

[root@ ~]# echo "http://domain:8080/test" | grep -Eo "(https?://)[^/]+"
http://domain:8080

在含有端口号的链接中只提取域名

echo "http://domain:8080/test" | grep -Eo "(https?://)[^/]+"
效果如下

[root@ ~]# echo "http://domain:8080/test" | grep -Eo "(https?://)[^/]+"
http://domain:8080

替换成另一个域名

sed -r 's|(https?://)[^/]+([[^:blank:]]*)|\1anotherdomain\2|g' test.txt
效果如下:

[root@ ~]# echo "https://domain:8080/test" > test.txt
[root@ ~]# sed -r 's|(https?://)[^/]+([[^:blank:]]*)|\1anotherdomain\2|g' test.txt
https://anotherdomain:8080/test

一些解释

(https?://)表示http://或者https://开头的字符串, [^/]+表示不包含/的一个以上字符串, 其中[:blank:]是空格或制表符

更多详细解释可以参考 https://wwwblogs/hb91/p/9969307.html

正则表达式在线验证工具

菜鸟教程的正则表达式工具 可以在线验证语法,还能快速生成其他语言的正则表达式代码
网址:
https://c.runoob/front-end/854/

更多推荐

提取及替换域名的正则表达式