【问题标题】:Is it possible to resolve SC2001 ("See if you can use ${variable//search/replace} instead") while using a position variable?使用位置变量时是否可以解决 SC2001(“看看是否可以使用 ${variable//search/replace}”)?
【发布时间】:2019-07-07 21:29:08
【问题描述】:

我正在寻找一个单行来用变量替换替换变量字符串中变量位置的任何字符。我想出了这个可行的解决方案:

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,但我不清楚使用位置变量时的正确格式。 official documentation 似乎根本没有讨论在字符串中的定位。

这可能吗?

【问题讨论】:

  • “工作解决方案”通常不起作用。使用replacement='&'replacement=/ 进行测试。见Escape a string for a sed replace pattern
  • @pjh,是的 - 我在评论讨论中非常明确(现在显然已删除),在答案之前它绝不是一般情况下的解决方案; OP 表示这足以满足他们的用例,并要求将评论的建议作为答案发布。

标签: bash parameter-expansion shellcheck


【解决方案1】:

Bash 没有针对所有 sed 工具的一般情况替换(shellcheck wiki page for warning SC2001 承认这一点),但在某些特定情况下(包括所提出的情况)可以组合参数扩展以实现所需效果:

string=aaaaa
replacement=b
position=3
echo "${string:0:$(( position - 1 ))}${replacement}${string:position}"

在这里,我们将值拆分为子字符串:${string:0:$(( position - 1 ))} 是要替换的内容之前的文本,${string:position} 是该点之后的文本。

【讨论】:

  • 新字符串的表达式是正确的,但可以简化为${string:0:position-1}${replacement}${string:position}
  • 这与问题的实质无关,但echo 命令通常不起作用。使用string=nn ; replacement=- ; position=1 进行测试。
猜你喜欢
  • 2015-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 2012-01-25
  • 2020-07-22
  • 2015-07-25
相关资源
最近更新 更多