我正在寻找一个衬里,用可变替代品替换可变位置的变量字符串中的任何字符。我想出了这个工作解决方案:
echo "$string" | sed "s/./${replacement}/${position}"
一个示例用法:
string=aaaaa
replacement=b
position=3
echo "$string" | sed "s/./${replacement}/${position}"
aabaa
不幸的是,当我用一个包含我当前解决方案的脚本运行ShellCheck时,它会告诉我:
SC2001: See if you can use ${variable//search/replace} instead.
我想像建议的那样使用参数扩展,而不是将管道扩展到SED,但是我尚不清楚使用位置变量时正确的格式。官方文档似乎根本没有讨论在字符串中的定位。
这是可能的吗?
bash没有所有SED设施的通用替代品(ShellCheck Wiki Wiki Page SC2001都认可了很多),但是在某些特定情况下 - 包括构成的情况 - - 参数扩展可以合并以达到所需的效果:
string=aaaaa
replacement=b
position=3
echo "${string:0:$(( position - 1 ))}${replacement}${string:position}"
在这里,我们将值分配到子字符串中: ${string:0:$(( position - 1 ))}
是要替换内容之前的文本,而 ${string:position}
是以下文本。