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

如何修正Bash case扩展正则以匹配主机名前缀并忽略后续字符

修正Bash Extglob正则匹配主机名

问题分析

你的原extglob模式 presto-data+([[:digit:]]) 仅匹配完整字符串等于presto-dataN(N为数字)的主机名,而presto-data1-01这类带-XX后缀的主机名无法匹配,因为模式没有允许后续字符存在。

修正后的模式

通用匹配(允许后缀为任意字符)

如果只需要确保主机名以presto-data加数字开头,后续内容不限制,使用:

presto-data+([[:digit:]])*

精准匹配(仅允许-XX数字后缀)

如果要严格限定后缀是-加数字的格式,用:

presto-data+([[:digit:]])-+([[:digit:]])

验证示例

针对你的主机名示例:

  • presto-data1-01、presto-data2-02均能被上述两种模式匹配
  • 原模式仅匹配presto-data1、presto-data2这类无后缀的主机名

额外技巧:提取前缀部分

如果脚本需要提取presto-dataN前缀(忽略-01这类后缀),无需正则,直接用Bash参数扩展更高效:

hostname="presto-data1-01"
prefix=${hostname%-*}  # 结果为presto-data1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 10:03:19