FreeKB - Linux Commands sed (replace string)
Linux Commands - sed (replace string)

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.

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


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


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