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

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

其他回答

小而通用的解决方案:

expr "$string" : "$prefix\(.*\)$suffix"

使用=~操作符:

$ 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

你知道你的前缀和后缀的长度吗?在你的情况下:

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的解决方案非常酷!我不知道!

我使用grep从路径中删除前缀(sed处理不好):

echo "$input" | grep -oP "^$prefix\K.*"

\K从匹配中删除它之前的所有字符。