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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
9 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
9 Comment authors
KarmakedarIliyan TrifonovasdJamie McNaught Recent comment authors
newest oldest most voted
asd
Guest
asd

brew install gnu-sed

Iliyan Trifonov
Guest
Iliyan Trifonov

Thanks!

Jamie McNaught
Guest
Jamie McNaught

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.

C
Guest
C

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 
Karma
Guest
Karma

GREAT, Exactly what i needed. Works on mac as well btw ?

Kirow
Guest
Kirow

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

kedar
Guest
kedar

Thanks! You saved my day! Stupid MacOS :/

trackback
Linux Search and Replace example

[…] sed command hits “undefined label” error on Mac OS X Tags: Unix / Linux Cory Berg Cory Berg has been a professional software engineer for 20 years, in a variety of different roles, and with a variety of technologies. His software has been used on airplanes, in armies, and in some of the largest technology companies in the world. You might also like following tutorials : JDBC TutorialsJava MongoDB TutorialsJava RegEx TutorialsApache Wicket Tutorials […]

Timothy Mwirabua
Guest
Timothy Mwirabua

Thanks!

Andrey
Guest
Andrey

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

Featured Posts