sed command hits “undefined label” error on Mac OS X

See following scenario, create a file, add content, search and replace it.

 
$ touch testing.txt
$ echo "this is mkyong.com" > testing.txt 
$ cat testing.txt 
this is mkyong.com
$ sed -i 's/mkyong/google/g' testing.txt 
sed: 1: "testing.txt": undefined label 'esting.txt'

This sed -i 's/mkyong/google/g' testing.txt command is working properly in Linux, but hits “undefined label” error message on Mac OS X.

Solution

The sed command is a bit different in Mac OS X, the ‘-i’ option required a parameter to tell what extension to add for the backup file.

To fix it, just add extension for backup file, for example ‘.bak’ :


$ sed -i '.bak' 's/mkyong/google/g' testing.txt 
$ ls -ls
8 -rw-r--r--  1 mkyong  staff  19 Aug  2 14:22 testing.txt
8 -rw-r--r--  1 mkyong  staff  19 Aug  2 14:21 testing.txt.bak
$ cat testing.txt
this is google.com
$ cat testing.txt.bak 
this is mkyong.com

13 comments on “sed command hits “undefined label” error on Mac OS X

  1. you can also just supply an empty string instead of ‘.bak’ to save no backup according to the man page

    Reply
  2. Very helpful, but if there is a space between -i and the SUFFIX for backup then it won’t work on Linux (well, Ubuntu anyway) but will on OSX.

    So instead of:
    sed -i ‘.bak’ ‘s/Hello/Goodbye/’ /tmp/jamie.txt

    do:
    sed -i’.bak’ ‘s/Hello/Goodbye/’ /tmp/jamie.txt
    ^ notice the lack of a space!

    This then works on both Linux and Mac.

    Reply
    1. In case we don’t want backup file, we will give -i “” . If we remove space here, it doesn’t work on mac.
      So on mac,
      sed -i’.bak’ ‘s/Hello/Goodbye/’ /tmp/jamie.txt ==> This works
      sed -i’’ ‘s/Hello/Goodbye/’ /tmp/jamie.txt ==> This doesn’t work

      Reply
  3. Thanks! What would we do without the internet at times..

    Reply
  4. Thank you man! Also if we don’t need backup file – we can execute sed -i ”

    Reply
  5. Back on the linux platform (not sure about Mac), if the replacement text contains slashes itself, you can do this – just use a different delimiter for those three original slashes:

     sed -i '.bak' 's#oldtext#new/text/with/slash#g' testing.txt 
    
    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *