Ale*_*sen 3 bash parameter-expansion shellcheck
我正在寻找一个单行代码来替换变量字符串中变量字符串中变量位置的任何字符。我想出了这个工作解决方案:
echo "$string" | sed "s/./${replacement}/${position}"
Run Code Online (Sandbox Code Playgroud)
示例用法:
string=aaaaa
replacement=b
position=3
echo "$string" | sed "s/./${replacement}/${position}"
aabaa
Run Code Online (Sandbox Code Playgroud)
不幸的是,当我使用包含我当前解决方案的脚本运行 shellcheck 时,它告诉我:
SC2001: See if you can use ${variable//search/replace} instead.
Run Code Online (Sandbox Code Playgroud)
我想使用它建议的参数扩展而不是管道到 sed,但我不清楚使用位置变量时的正确格式。在官方文档似乎并没有讨论在所有字符串中的定位。
这可能吗?
Bash 没有对所有 sed 设施进行一般情况替换(警告 SC2001的 shellcheck wiki 页面也承认这一点),但在某些特定情况下——包括所提出的情况——可以组合参数扩展来达到预期的效果:
string=aaaaa
replacement=b
position=3
echo "${string:0:$(( position - 1 ))}${replacement}${string:position}"
Run Code Online (Sandbox Code Playgroud)
在这里,我们将值拆分为子字符串:${string:0:$(( position - 1 ))}是要替换的内容之前的文本,以及${string:position}该点之后的文本。