sed in-place editing (-i) difference on Mac OS X: “undefined label” errors

May 27, 2010

I ran into this problem about a month ago with a bash script that I was writing on my MacBook Pro.  For some reason, sed in place editing with ‘sed -i‘ just wouldn’t work, no matter what I did, and I couldn’t find any solution online.

When running something like

sed -i 's/before/after/' test.txt

you get the error message sed: 1: "test.txt": undefined label 'est.txt'.

Eventually, it turned out to be because sed’s ‘-i‘ option takes a parameter to indicate what extension to add to the file name when making a backup.  For example,

sed -i '.bak' 's/before/after/' test.txt

leaves you with two files, ‘test.txt‘ and ‘test.txt.bak‘, where ‘test.txt.bak‘ is the original version.  Unlike Ubuntu and other linux versions, on OS X, this extension parameter is required.  If you really know what you’re doing and don’t want a backup made, you need to provide an empty string ”.

The correct way to run this command on OSX is

sed -i '' 's/before/after/' test.txt

Advertisement

6 Responses to “sed in-place editing (-i) difference on Mac OS X: “undefined label” errors”

  1. BlueSherpa Says:

    Thanks! I ran into this same issue. Your post helped!

    • Mike Says:

      Awesome! I’m glad you didn’t have to spend as much time as I did figuring it out!

  2. Mike Says:

    Hey thanks..! Helped a lot

  3. pawlik Says:

    Thanks for sharing ;)

  4. jerrrry Says:

    another way is:
    sed ‘s/before/after/’ -i — test.txt

  5. mconigliaro Says:

    Thanks! This thing was driving me nuts.


Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.