bash字符串截取方式
在处理 Bash 变量、文件路径、参数解析 时非常实用。
| 语法 | 作用 | 示例 | 结果 |
|---|---|---|---|
${var#prefix} |
删除左侧最短匹配 | "hello-world" → ${var#*-} |
"world" |
${var##prefix} |
删除左侧最长匹配 | "hello-world-example" → ${var##*-} |
"example" |
${var%suffix} |
删除右侧最短匹配 | "hello-world-example" → ${var%-*} |
"hello-world" |
${var%%suffix} |
删除右侧最长匹配 | "hello-world-example" → ${var%%-*} |
"hello" |
${var:offset} |
从 offset 处截取 |
"hello-world" → ${var:6} |
"world" |
${var:offset:length} |
从 offset 开始截取 length 个字符 |
"hello-world" → ${var:6:3} |
"wor" |
${#var} |
获取字符串长度 | "hello-world" → ${#var} |
11 |
${var/pattern/replacement} |
替换第一个匹配项 | "hello world world" → ${var/world/planet} |
"hello planet world" |
${var//pattern/replacement} |
替换所有匹配项 | "hello world world" → ${var//world/planet} |
"hello planet planet" |
浙公网安备 33010602011771号