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

求KSH参数扩展中\n替换功能的可用实操示例

KSH 参数扩展\n反向引用替换功能实操示例

所有示例均在ksh93环境测试可正常运行,替换规则符合你提到的参数扩展语法:

${parameter/pattern/string}
${parameter//pattern/string}
${parameter/#pattern/string}
${parameter/%pattern/string}

其中替换字符串内的\n(n为从1开始的正整数)会按顺序匹配pattern里用()包裹的第n个子模式捕获的内容。


示例1:基础单分组捕获替换

# 定义测试变量
test_str="order_20240512_user001.csv"
# 捕获下划线中间的日期字段,用\1引用
result=${test_str/*_(*)_*_*.csv/date:\1}
echo $result

运行输出:

date:20240512

示例2:多分组捕获多\n引用

test_str="2024-05-12:user001:download:file123.pdf"
# 3个分组分别捕获日期、用户名、文件名
result=${test_str/(*):(*):*:(*)/用户\2在\1下载了文件\3}
echo $result

运行输出:

用户user001在2024-05-12下载了文件file123.pdf

示例3:结合全局替换的反向引用

test_str="apple red, banana yellow, grape purple"
# 全局匹配所有「水果 颜色」结构,交换两者顺序
result=${test_str//(*)/\2 \1}
echo $result

运行输出:

red apple, yellow banana, purple grape

示例4:结合前缀/后缀匹配的反向引用

# 前缀匹配场景:提取链接域名
test_str="https://www.example.com/path/to/file.html"
result=${test_str/#https:\/\/(*)\//\1站点资源跳转}
echo $result

# 后缀匹配场景:提取文件版本号
test_str="user_report_202405_v2.pdf"
result=${test_str/%_v(*).pdf/版本号:\1}
echo $result

运行输出:

www.example.com站点资源跳转
user_report_202405版本号:2

注意事项

若需要输出字面量的\+数字,需要对反斜杠做转义,写成\\n即可:

test_str="test123"
result=${test_str/test/\\1:}
echo $result

运行输出:

\1:123

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:45:03