我有“我爱Suzi和Marry”,我想把“Suzi”改成“Sara”。
firstString="I love Suzi and Marry"
secondString="Sara"
预期的结果:
firstString="I love Sara and Marry"
我有“我爱Suzi和Marry”,我想把“Suzi”改成“Sara”。
firstString="I love Suzi and Marry"
secondString="Sara"
预期的结果:
firstString="I love Sara and Marry"
当前回答
使用${parameter/pattern/string}替换模式的第一次出现:
#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/"$secondString"}"
# prints 'I love Sara and Marry'
使用${parameter//pattern/string}替换所有出现的情况:
message='The secret code is 12345'
echo "${message//[0-9]/X}"
# prints 'The secret code is XXXXX'
(这在Bash参考手册§3.5.3“Shell参数扩展”中有记录。)
注意这个特性不是POSIX指定的——它是一个Bash扩展——所以不是所有Unix shell都实现它。有关POSIX的相关文档,请参见Open Group技术标准基础规范,第7期,Shell & Utilities卷,§2.6.2“参数扩展”。
其他回答
因为我不能添加评论。为了使示例更具可读性,可以这样写
full_string="I love Suzy and Mary"
search_string="Suzy"
replace_string="Sara"
my_string=${full_string/$search_string/$replace_string}
or
my_string=${full_string/Suzy/Sarah}
对于Dash,之前的所有帖子都不起作用
POSIX sh兼容的解决方案是:
result=$(echo "$firstString" | sed "s/Suzi/$secondString/")
这将替换每一行输入中的第一个出现的位置。添加/g标记替换所有出现的情况:
result=$(echo "$firstString" | sed "s/Suzi/$secondString/g")
试试这个:
sed "s/Suzi/$secondString/g" <<<"$firstString"
试试这个:
ls *.ext | awk '{print "mv "$1" "$1".newext"}' | sed "s/.ext.newext/.newext/" | parallel {}
纯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.