Replace text in a variable using SED in Linux

Home > Search

The sed command with the s (substitue) option can be used to change text in a file or a variable. Let's say that foo contains the text Hello World.

foo="Hello World"


The sed command with the s (substitute) flag is used to replace data. In this example, the text "Hi" will be replaced with the text "Hello".  It is also important to recongize that with this syntax, the text in the variable will not be changed. Instead, the result will simply be displayed in the terminal. 

~]# 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.

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


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.