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

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.



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


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

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


Web design by yours truely - me, myself, and I   |   |