我在理解Bash中的str-replacement函数时遇到问题。我来自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"
当我保存为脚本时;替换.sh";并运行它,然后它打印:
/更换.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"
```
这是bash替换模式,在变量subject
中替换所有出现的"身体;用";黑色";。
由于//
,所有出现的情况下,单斜杠将只替换第一个出现的情况。也许这个例子会让它变得更清楚:
$ 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