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.
krypted February 7th, 2011
Posted In: Mac OS X, Ubuntu
find and replace, interactive, Mac OS X, scripting, sed, text substitution