我有“我爱Suzi和Marry”,我想把“Suzi”改成“Sara”。

firstString="I love Suzi and Marry"
secondString="Sara"

预期的结果:

firstString="I love Sara and Marry"

当前回答

使用sed我们可以很容易地做到这一点

sed -i "s+$value_to_be_replaced+$with_variable1 "some character" $with_variable2+g" $file_name

其他回答

纯POSIX shell方法,与Roman Kazanovskyi基于sed的答案不同,它不需要外部工具,只需要shell自己的本地参数展开。注意,长文件名被最小化,所以代码更适合一行:

f="I love Suzi and Marry"
s=Sara
t=Suzi
[ "${f%$t*}" != "$f" ] && f="${f%$t*}$s${f#*$t}"
echo "$f"

输出:

I love Sara and Marry

工作原理:

Remove Smallest Suffix Pattern. "${f%$t*}" returns "I love" if the suffix $t "Suzi*" is in $f "I love Suzi and Marry". But if t=Zelda, then "${f%$t*}" deletes nothing, and returns the whole string "I love Suzi and Marry". This is used to test if $t is in $f with [ "${f%$t*}" != "$f" ] which will evaluate to true if the $f string contains "Suzi*" and false if not. If the test returns true, construct the desired string using Remove Smallest Suffix Pattern ${f%$t*} "I love" and Remove Smallest Prefix Pattern ${f#*$t} "and Marry", with the 2nd string $s "Sara" in between.

试试这个:

 sed "s/Suzi/$secondString/g" <<<"$firstString"
echo [string] | sed "s|[original]|[target]|g"

“s”表示“替换” “g”表示“全局的,所有匹配的事件”

使用AWK:

firstString="I love Suzi and Marry"
echo "$firstString" | awk '{gsub("Suzi","Sara"); print}'

使用sed我们可以很容易地做到这一点

sed -i "s+$value_to_be_replaced+$with_variable1 "some character" $with_variable2+g" $file_name