Replace values in a variable in BASH

Home > Search
  by

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

 



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 in the box below so that we can be sure you are a human.




Comments