I have \"I love Suzi and Marry\" and I want to change \"Suzi\" to \"Sara\".
#!/bin/bash
firstString=\"I love Suzi and Marry\"
secondString=\"Sara\"
# do some
To replace the first occurrence of a pattern with a given string, use ${parameter/pattern/string}
:
#!/bin/bash
firstString="I love Suzi and Marry"
secondString="Sara"
echo "${firstString/Suzi/$secondString}"
# prints 'I love Sara and Marry'
To replace all occurrences, use ${parameter//pattern/string}
:
message='The secret code is 12345'
echo "${message//[0-9]/X}"
# prints 'The secret code is XXXXX'
(This is documented in the Bash Reference Manual, §3.5.3 "Shell Parameter Expansion".)
Note that this feature is not specified by POSIX — it's a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see The Open Group Technical Standard Base Specifications, Issue 7, the Shell & Utilities volume, §2.6.2 "Parameter Expansion".
If tomorrow you decide you don't love Marry either she can be replaced as well:
today=$(</tmp/lovers.txt)
tomorrow="${today//Suzi/Sara}"
echo "${tomorrow//Marry/Jesica}" > /tmp/lovers.txt
There must be 50 ways to leave your lover.
try this:
sed "s/Suzi/$secondString/g" <<<"$firstString"
Since I can't add a comment. @ruaka To make the example more readable write it like this
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}