Replace text with sed


This post goes over how to replace text with sed.

Prerequisites

Given file with content:

echo 'Hello world!' > file.txt

Replace without file modification

To replace the first match of l with r:

sed 's/l/r/' file.txt
Herlo world!

To globally replace all matches of l with r:

sed 's/l/r/g' file.txt
Herro worrd!

To replace multiple patterns:

sed 's/ /, /; s/!/./' file.txt
Hello, world.

Replace with file modification

To replace Hello with Hi:

sed -i '' 's/Hello/Hi/' file.txt
cat file.txt
Hi world!

To replace and modify the file and create a copy of the original file:

sed -i .original 's/Hi/Hey/' file.txt
cat file.txt
Hey world!
cat file.txt.original
Hi world!


Please support this site and join our Discord!