Mass find and replace on Mac OSX with SED

Lets say you are doing some grand refactoring, and you want to change a class name from Dog to Pooch in multiple files.
There are a couple of ways you can do it with the sed command. One uses the -exec argument and the other uses the xargs program. Though I'm not sure why, I favor the xargs strategy. In Linux to do a mass find and replace for our Dog to Pooch example you could do something like:
find . -name "*.php" -print | xargs sed -i 's/Dog/Pooch/g'

But if you try this same command In Mac OSX you will see an error like this:
extra characters at the end of g command

The reason for this is the command in Mac OSX the command doesn't trust you. I wonder if rm -rf / works in Mac OSX? Well I'm not going to find out ;-) Mac OSX will create a backup file in case you mess up your find and replace, and it requires an extension for this file. With that in mind, the following command will work in Mac OSx:
find . -name "*.php" -print | xargs sed -i.bak 's/Dog/Pooch/g'

I recommend you choose a unique backup extension so that you can easily delete all the backup files. Once your happy with your change of course you can run something like: find . -name '*.bak' | xargs rm



  1. If you pass "" after the -i flag it will modify in place.

    find . -name "*.php" -print | xargs sed -i "" 's/Dog/Pooch/g'

    I also prefer xargs when using the command line since it involves less typing, but it's worth noting that -exec is a builtin, which should be faster than piping to xargs.


Post a Comment

Popular posts from this blog

Android: How to change size of vector drawable image

AngularJs: User friendly date display with AngularJs and MomentJs

Nerd Tree: A File Explorer with Mac Vim