Question: ❓❓❓


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 something...

The result must be like this:

firstString="I love Sara and Marry"


Good Answer: 👌👌👌

To replaced the first occurrence of a string (regular expression actually), use ${string/regexp/replacement}:

#!/bin/bash
original_string='I love Suzy and Mary'
string_to_replace_Suzy_with='Sara'
result_string="${original_string/Suzy/$string_to_replace_Suzy_with}"

To replace all matches of $pattern with $replacement, double the first slash:

string="The secret code is 12345"
pattern="[0-9]"
echo ${string//$pattern/X}  # The secret code is XXXXX

Make sure the script is executed with bash. Other shells (e.g. sh) may return “Bad substitution”.


Read More: 👉 https://stackoverflow.com/questions/13210880/replace-one-substring-for-another-string-in-shell-script

Categories: developerknowledge