Quick & Dirty sed Find/Replace

I find a very common task that I need to do is find a string in a file and replace it with another string. Or better, find all instances of a given string and replace them with a new string. I figure others will need to do this as well. This is also an interesting example of how Mac OS X is not “the same” as Linux.

The sed command can be used to quickly perform a find and replace inside of a file. The following example will use the -i option to do so in-place, defining no extensions to -i using the double quotes (“”), then using the /s to instruct a substitution of the pattern to match followed by the pattern to replace (in this case we’re finding like and replacing it with love in celebration of the upcoming Valentines Day) and doing so globally, or for all instances using the /g option. The find and replace will be performed inside of the file called /Users/krypted/test:
sed -i "" 's/like/love/g' /Users/krypted/test
Because things can go wrong during the edit, such as an OS crash, it is always smart to make a backup of your file before you change it. By appending a .backup to the -i option, sed will get instructed to make a backup:
sed -i.backup -e 's/like/love/g' /Users/krypted/test
By default in Linux, the command would work with or without the double quotes (“”) that I used to define the extension; however, as mentioned Mac OS X is not Linux; you have to define an extension or the command will error out. Overall, finding and replacing or substituting text within a file is a very common systems administration task and the above command is a very simplistic approach to performing such a task.

4 Comments

  • February 7, 2011 - 9:03 am | Permalink

    the -i option is an “in place” edit, not “interactive.

  • Karl Kuehn
    February 7, 2011 - 1:30 pm | Permalink

    But ‘sed’ is evil! Couldn’t you have done this example in a good, God fearing text processor like ‘grep’ or ‘awk’?

    *grin*

  • vivek
    June 1, 2012 - 12:28 am | Permalink

    Saved me!!!

    Thanks a lot

  • Comments are closed.