Bash (Scripting) - replace values in a variable

by
Jeremy Canfield |
Updated: March 08 2020
| Bash (Scripting) articles
Let's say you have a variable in bash that already contains values.
foo="Hello World"
This works well if you don't need to use sed and regular expressions.
foo="${foo/World/Earth}"
This works well if you want to use a regular expression in the replacement. Ensure you double quote your variable ("$foo" in this example). This Unix and Linux Stack Exchange article explains the reasoning for this.
foo=$( echo "$foo" | sed "s|World|Earth|" )
Or, sed and <<< can be used to replace values in the variable. In this example, the word World is replaced with the word Earth.
foo=$( sed "s|World|Earth|" <<< "$foo" )
Printing the variable will now print the following.
Hello Earth
Did you find this article helpful?
If so, consider buying me a coffee over at