Skip to content

Lesson 19: Text Substitution

Stream editor (sed) can be used to find and replace text. The pattern to be replaced can be either a string literal, or a regular expression.

One of the most common uses for sed is word substitution. The syntax for this operation is sed 's/old/new/g' where old is the word to be substituted with the word new. The letter g in the command instructs sed to substitute all matches (global) found. If this is omitted, sed will only replace the first match found.

Let's replace the word 'found' with the word 'discovered' globally in the 'earth.txt' file:

[learner planets]$ sed 's/found/discovered/g' earth.txt
...
The highest point discovered on Earth is Mount Everest.
...

Running the above command will only display the change in the terminal. If the change needs to be permanent, pass the -i switch to edit files "in place"

Below is an example regular expression on the 'earth.txt' file, replacing all lines which begin with the letter E with the solar system fact. The caret symbol (^) represents "that starts with".

[learner planets]$ sed -i 's/^E.*/Earth is the third planet in the solar system./g' earth.txt
[learner planets]$ cat earth.txt
Earth is the third planet in the solar system.
Earth is the third planet in the solar system.
Earth is the third planet in the solar system.
The highest point found on Earth is Mount Everest.
70% of the Earth’s surface is covered by water.

Adding the .bak suffix to the -i switch takes a backup of the original file before the substitution is made.