使用三个变量将 Str 替换为 Bash 代码块:搜索、替换和主题

时间:2021-05-20 11:44:04

标签: r

我在理解 Bash 中的 str 替换函数时遇到问题。 我来自 PHP,其中函数名为 str_replace

谁能帮我举个例子:

search="%body%" # The value being searched for, otherwise known as the needle
replace="black" # The replacement value that replaces found search values
subject="<body text='%body%'>" # The string or array being searched and replaced on, otherwise known as the haystack

new_string=`echo ${subject//$search/$replace}`
echo "$new_string"

当我保存为脚本“replace.sh”并运行它时,它会打印:

./replace.sh

<body text='black'>

当我将它作为代码块放入 R Studio 时,它不会打印任何内容:

```{bash echo=FALSE, comment="", results="asis", message=FALSE, tidy=FALSE}
search="%body%" # The value being searched for, otherwise known as the needle
replace="black" # The replacement value that replaces found search values
subject="<body text='%body%'>" # The string or array being searched and replaced on, otherwise known as the haystack

new_string=`echo ${subject//$search/$replace}`
echo "$new_string"
```

1 个答案:

答案 0 :(得分:1)

这是 bash 替换模式,在变量 subject 中将所有出现的“body”替换为“black”。

所有出现都是因为 //,单斜杠只会导致第一个出现被替换。也许这个例子会更清楚:

$ string="aaaaa"
$ echo $string
aaaaa
$ echo ${string/a/b}
baaaa
$ echo ${string//a/b}
bbbbb

更多信息在这篇不错的文章中,请参阅第 5 章:

https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html