Sam Doran

My little corner of the Internet

sed on Mac OS X

I was doing some file manipulation using sed on OS X the other day and this subtle difference between the BSD and GNU versions tripped me up.

This is how to edit a file in place using GNU sed:

sed -i 's/[find regex]/[replace string]/g' filename.txt

On OS X, using the above command gives the an invalid command code or undefined label error. Not very helpful. Man page to the rescue.

 -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.

In OS X, the -i flag requires a file extension parameter — it’s optional in GNU.

sed -i txt 's/[find regex]/[replace string]/g' filename.txt

If the file does not have an extension, then use two single quotes.

sed -i '' 's/[find regex]/[replace string]/g' filename

I’m sure there are many other subtle differences between BSD and GNU sed but this is a pretty common one.