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

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

如何得到以下结果?

"o-wor"

当前回答

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

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

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

其他回答

注:不确定这在2013年是否可能,但今天(2021年10月10日)肯定是可能的,所以增加了另一个选项…


由于我们处理的是已知的固定长度字符串(前缀和后缀),因此可以使用bash子字符串通过单个操作获得所需的结果。

输入:

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

计划:

Bash子字符串语法:${字符串:<开始>:<长度>} 跳过prefix="hell"意味着我们的<start>将是4 <length>将是字符串的总长度(${#string})减去固定长度的字符串长度(hell为4 / ld为2)

这给了我们:

$ echo "${string:4:(${#string}-4-2)}"
o-wor

注意:可以删除paren,仍然得到相同的结果


如果prefix和suffix的值未知,或者可能会变化,我们仍然可以使用相同的操作,但将4和2分别替换为${#prefix}和${#suffix}:

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

$ #remove "hell" from "hello-world" if "hell" is found at the beginning.
$ prefix_removed_string=${string/#$prefix}

$ #remove "ld" from "o-world" if "ld" is found at the end.
$ suffix_removed_String=${prefix_removed_string/%$suffix}
$ echo $suffix_removed_String
o-wor

注:

#$prefix:添加#确保子字符串“hell”只在开头被发现时才被删除。 %$后缀:添加%确保子字符串“ld”只有在end中找到时才会被删除。

如果没有这些,子字符串“hell”和“ld”将被删除,即使它是在中间找到的。

使用=~操作符:

$ string="hello-world"
$ prefix="hell"
$ suffix="ld"
$ [[ "$string" =~ ^$prefix(.*)$suffix$ ]] && echo "${BASH_REMATCH[1]}"
o-wor

小而通用的解决方案:

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

对阿德里安早餐满意:

function strip {
    local STRING=${1#$"$2"}
    echo ${STRING%$"$2"}
}

像这样使用它

HELLO=":hello:"
HELLO=$(strip "$HELLO" ":")
echo $HELLO # hello