Replace text with sed


Given file with content:

$ echo 'Hello world!' > file.txt

To replace the first match of l with r (without file modification):

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

To globally replace all matches of l with r (without file modification):

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

To replace multiple patterns (without file modification):

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

To replace Hello with Hi with file modification:

$ 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!


If you enjoyed this post, please consider supporting this site!