How to use sed to replace text in a file.

dos2unix

Well-Known Member
Joined
May 3, 2019
Messages
3,527
Reaction score
3,294
Credits
31,550

Example Text File​

Let's create a file named example.txt with the word "Worshington" in it several times.

Worshington is a beautiful city.
Many people visit Worshington every year.
The history of Worshington is fascinating.

Using sed to Replace "Worshington" with "Washington"​

Replace in Place​

To replace "Worshington" with "Washington" in the existing file and save the changes in the same file, use the following command:

Code:
 sed -i 's/Worshington/Washington/g' example.txt

Create a New File​

To replace "Worshington" with "Washington" and save the changes in a new file while keeping the original file unchanged, use the following command:

Code:
 sed 's/Worshington/Washington/g' example.txt > new_example.txt

The -i means insert in place. The s means search for. The g means do it globally ( everywhere in the file )
If you leave the g option out, if will just replace the first word, not all of the words.

These commands will help you replace the word "Worshington" with "Washington" globally in the text file.
 
Last edited:



Top