Bootstrap FreeKB - Bash (Scripting) - replace values in a variable
Bash (Scripting) - replace values in a variable

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter ff9b3f in the box below so that we can be sure you are a human.