Let's say that foo contains a value of Hello World.
foo="Hello World"
The sed command with the s (substitue) option can be used to performs a replacment in a file or a variable.
In this example, the text "Hello" will be replaced with the text "Hi". When the -i flag is not used, the change will not actually be made. In this way, this is a sort of test that can be used to see the change, but not commit the change.
echo $foo | sed 's|Hello|Hi|'
. . .
Hi World
With this syntax, Hello will be replaced with Hi in the foo variable.
foo=$( sed "s|Hello|Hi|" <<< "$foo" )
This does the same.
foo=$( echo "$foo" | sed "s|Hello|Hi|" )
Replace multiple instances of a string (global)
If a variable contains more than one occurence of a string, the g (global) option will need to be used to change every instance of the string. For example, let's say a foo contains the following text.
foo="
Hello World
Hello World
Hello World"
If the g (global) flag is not used, only the first instance of the word Hello will be changed.
~]# echo $foo | sed 's/Hello/Hi/'
Hi World
Hello World
Hello World
The g (global) flag will change every instance of Hello to Hi.
~]# echo $foo | sed 's/Hello/Hi/g'
Hi World
Hi World
Hi World
Multiple different replacements
In this example, Hello becomes Hi and World becomes Earth, in a single inline command.
echo $foo | sed 's|Hello|Hi|; s|World|Earth|'
. . .
Hi Earth
Did you find this article helpful?
If so, consider buying me a coffee over at