· shell-scripting-2

Sed: 'sed: 1: invalid command code R' on Mac OS X

A few days ago I wrote about how we’d been using Sed to edit multiple files and while those examples were derived from what we’d been using on Ubuntu I realised that they didn’t actually work on Mac OS X.

For example, the following command:

sed -i 's/require/include/' Rakefile

Throws this error:

sed: 1: "Rakefile": invalid command code R

What I hadn’t realised is that on the Mac version of sed the ‘-i’ flag has a mandatory suffix, as described in this post.

The appropriate section of the man page for sed on the Mac looks like this:

-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 togive a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.

Whereas on Ubuntu the suffix is optional so we see this:

-i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied)

In order to get around this we need to provide a blank suffix when using the ‘-i’ flag on the Mac:

sed -i "" 's/require/include/' Rakefile

I didn’t RTFM closely enough the first time!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket