替换字符串中最后一次出现的子字符串 (bash)

Replace Last Occurrence of Substring in String (bash)

来自bash软件手册:

${parameter/pattern/string}

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string.
... If pattern begins with ‘%’, it must match at the end of the expanded value of parameter.

所以我试过了:

local new_name=${file/%old/new}

其中string是绝对文件路径(/abc/defg/hijoldnew是可变字符串。

然而,这似乎是在尝试匹配文字 %sb1

这个的语法是什么?

预期输出:

给定

old=sb1
new=sb2

然后

/foo/sb1/foo/bar/sb1 应该变成 /foo/sb1/foo/bar/sb2

/foo/foosb1other/foo/bar/foosb1bar 应该变成 /foo/foosb1other/foo/bar/foosb2bar

仅使用 shell-内置 parameter expansion:

src=sb1; dest=sb2
old=/foo/foosb1other/foo/bar/foosb1bar

if [[ $old = *"$src"* ]]; then
  prefix=${old%"$src"*}                  # Extract content before the last instance
  suffix=${old#"$prefix"}                # Extract content *after* our prefix
  new=${prefix}${suffix/"$src"/"$dest"}  # Append unmodified prefix w/ suffix w/ replacement
else
  new=$old
fi

declare -p new >&2

...正确发出:

declare -- new="/foo/foosb1other/foo/bar/foosb2bar"