Using `sed` command in Mac OS X to accomplish ‘replace in files’ in CUI

It’s easy to use sed command, right?

%: sed -i "s/old/replace/g" mysql.txt

This tip is all around the net. But! it doesn’t work with Mac!

WTF? How to make it work?

Try it yourself, I’m using Lion 10.7.3, it cost me over 30 minutes to search and read the man page.

-i extension

Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.

What is a zero-length extension? Try this:

%: sed -i "" "s/old/replace/g" mysql.txt

The empty string behind -i as -i "" is the KEY point.

Replace in multiple files

Try this:

%: find path/to/search -name "*.php" -exec sed -i "" "s/old/replace/g" {} \;

Good luck! Don’t forget to follow me @TonnyXu

Be Sociable, Share!
    • Tonny Xu

      Shit, I forgot I wrote this before!!! And I googled and my post was popped out!

    • http://twitter.com/ghawkgu Yi Gu

      I recommend you try the GNU sed which can be installed with “brew install gnu-sed”. 

      • Tonny Xu

        Wow, I didn’t know this tool, looks like much more better then default `sed` command