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!