gpt4 book ai didi

bash - 从 Bash 中的字符串中删除固定前缀/后缀

转载 作者:行者123 更新时间:2023-11-29 08:36:56 26 4
gpt4 key购买 nike

我想从字符串中删除前缀/后缀。例如,给定:

string="hello-world"
prefix="hell"
suffix="ld"

如何得到下面的结果?

"o-wor"

最佳答案

$ prefix="hell"
$ suffix="ld"
$ string="hello-world"
$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor

这记录在 Shell Parameter Expansion 中手册部分:

${parameter#word}
${parameter##word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the # case) or the longest matching pattern (the ## case) deleted. […]

${parameter%word}
${parameter%%word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the % case) or the longest matching pattern (the %% case) deleted. […]

关于bash - 从 Bash 中的字符串中删除固定前缀/后缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16623835/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com