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

Updated:   |  Linux Commands articles

sed can be used to replace some value with some other value. For example, to replace "Hello" with "Goodbye". The "s" here stands for "substitute".

~]$ echo "Hello World" | sed 's/Hello/Goodbye/'
Goodbye World

 

Instead of using the forward slash delimiter, you can use the pipe delimiter.

~]$ echo "Hello World" | sed 's|Hello|Goodbye|'
Goodbye World

 

More practically, this is often used to replace some value in a file. For example, let's say example.txt contains "Hello World".

~]$ cat example.txt
Hello World

 

When the -i or --in-place flag is NOT used, the change will not actually be made. In this example, the stdout just shows what the sed command would do, but doesn't actually make the change in the file.

~]$ sed 's|Hello|Goodbye|' example.txt
Goodbye World

 

The -i or --in-place flag will make the change to the file.

sed -i 's|Hello|Goodbye|' example.txt

 

Be aware that sometimes this may change the owner of the file, perhaps from john.doe to nobody.

~]$ ls -l example.txt
-rw-rw-r--. 1 nobody users 224 May  1 21:40 example.txt

 

The -c or --copy flag can be used to preserve the owner of the file.

sed --copy -i 's|Hello|Goodbye|' example.txt

 

In this example, "Hello" will be replaced with the text "Goodbye" in the $foo variable.

~]$ foo="Hello World"
~]$ echo $foo
Hello World
~]$ foo=$( sed "s|Hello|Hi|" <<< "$foo" )
~]$ echo $foo
Goodbye World

 

This does the same.

~]$ foo="Hello World"
~]$ echo $foo
Hello World
~]$ foo=$( echo "$foo" | sed "s|Hello|Goodbye|" )
~]$ echo $foo
Goodbye World

 

If a string, variable or file contains more than one occurence of a pattern, the g (global) can be used to change every occurrence of a pattern. 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/Goodbye/'
Goodbye World
Hello World
Hello World

 

The g (global) flag will change every instance of Hello to Goodbye.

~]# echo $foo | sed 's/Hello/Goodbye/g'
Goodbye World
Goodbye World
Goodbye World

 

You can string together multiple sed statements. 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

 

You can also use regular expressions. In this example, only lines beginning with Hello will be replaced with Goodbye.

~]$ cat example.txt
Hello World
World Hello

~]$ sed 's|^Hello|Goodbye|g' example.txt
Goodbye World
World Hello

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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