我想从字符串中删除前缀/后缀。例如,给定:
string="hello-world"
prefix="hell"
suffix="ld"
如何得到以下结果?
"o-wor"
我想从字符串中删除前缀/后缀。例如,给定:
string="hello-world"
prefix="hell"
suffix="ld"
如何得到以下结果?
"o-wor"
当前回答
对阿德里安早餐满意:
function strip {
local STRING=${1#$"$2"}
echo ${STRING%$"$2"}
}
像这样使用它
HELLO=":hello:"
HELLO=$(strip "$HELLO" ":")
echo $HELLO # hello
其他回答
我使用grep从路径中删除前缀(sed处理不好):
echo "$input" | grep -oP "^$prefix\K.*"
\K从匹配中删除它之前的所有字符。
你知道你的前缀和后缀的长度吗?在你的情况下:
result=$(echo $string | cut -c5- | rev | cut -c3- | rev)
或者更一般地说:
result=$(echo $string | cut -c$((${#prefix}+1))- | rev | cut -c$((${#suffix}+1))- | rev)
但是Adrian Frühwirth的解决方案非常酷!我不知道!
$ prefix="hell"
$ suffix="ld"
$ string="hello-world"
$ foo=${string#"$prefix"}
$ foo=${foo%"$suffix"}
$ echo "${foo}"
o-wor
这在手册的Shell参数扩展部分中有记录:
${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. […]
使用=~操作符:
$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ [[ "$string" =~ ^$prefix(.*)$suffix$ ]] && echo "${BASH_REMATCH[1]}"
o-wor
对阿德里安早餐满意:
function strip {
local STRING=${1#$"$2"}
echo ${STRING%$"$2"}
}
像这样使用它
HELLO=":hello:"
HELLO=$(strip "$HELLO" ":")
echo $HELLO # hello