Last Updated: February 25, 2016
· nicolaslazartekaqui
Img 3566

Sed - Find and replace with sed


Assuming that a file file.txt you want to replace where old to new, you can do

$ sed  's/old/new/g' file.txt

this way, known as preview, just prints the result of the replacement but not overwrite the file. To overwrite, use the param -i

$ sed -i 's/old/new/g' file.txt

or, if you want to do a backup from the file before replacing, you can use the param -i.bkp

$ sed -i.bkp 's/old/new/g' file.txt

this way it creates a file file.txt.bkp with the old version of the file.

In some more complicated cases you can use regular expression to replace data.

Get this in MAC OS?

command c expects \ followed by text

Use this

$ sed -i '' 's/old/new/g' file.txt

This happens because sed in MAC OS is a different BSD flavor.

More? http://www.gnu.org/software/sed/manual/sed.html

Say Thanks