You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shell脚本中如何从带IP和端口的URL提取基础地址?

提取URL中的基础地址方法

下面提供几种通用命令行工具的实现方式,能批量处理这类URL变量:

1. 使用sed命令

sed是文本替换的常用工具,通过正则匹配捕获目标部分:

提取带末尾斜杠的基础地址(匹配url1需求)

echo "url1='http://10.25.225.123:32782/actuator/health'" | sed -E "s/.*'(http:\/\/[^\/]+\/)[^']*'.*/\1/"

输出:http://10.25.225.123:32782/

提取不带末尾斜杠的基础地址(匹配url2需求)

echo "url2='http://10.25.225.321:12345/myappmanagement/health'" | sed -E "s/.*'(http:\/\/[^\/]+)\/[^']*'.*/\1/"

输出:http://10.25.225.321:12345

如果要批量处理多个URL(比如存放在urls.txt文件中),直接运行:

sed -E "s/.*'(http:\/\/[^\/]+\/?)[^']*'.*/\1/" urls.txt

该命令会自动适配两种格式:若URL端口后直接跟斜杠则保留,否则提取到端口为止。

2. 使用awk命令

awk通过分割字段提取内容,逻辑更直观:

echo "url2='http://10.25.225.321:12345/myappmanagement/health'" | awk -F"['/]" '{print $2"/"$3}'

输出:http://10.25.225.321:12345

如果要保留末尾斜杠,调整为:

echo "url1='http://10.25.225.123:32782/actuator/health'" | awk -F"'" '{split($2,a,"/"); print a[1]"/"a[2]"/"}'

输出:http://10.25.225.123:32782/

3. 使用grep命令

利用grep的正向预查和捕获功能,仅输出匹配的目标部分:

echo "url1='http://10.25.225.123:32782/actuator/health'" | grep -oP "(?<=')[^']*(?=\/[^\/]+')"

输出:http://10.25.225.123:32782

如果要保留末尾斜杠,修改正则:

echo "url1='http://10.25.225.123:32782/actuator/health'" | grep -oP "(?<=')[^']*(?=actuator')"

输出:http://10.25.225.123:32782/


内容的提问来源于stack exchange,提问作者Prem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 05:50:22