Main Tutorials

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 Author

author image
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

Subscribe
Notify of
13 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
asd
6 years ago

brew install gnu-sed

Jamie McNaught
6 years ago

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.

Nikhil
5 months ago
Reply to  Jamie McNaught

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

kedar
5 years ago

Thanks! You saved my day! Stupid MacOS :/

Kirow
9 years ago

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

Frank Lewis
2 years ago

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

C
11 years ago

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
5 years ago
Reply to  C

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

Prasanna
3 years ago

Thanks a lot !!!

Iliyan Trifonov
6 years ago

Thanks!

Andrey
6 years ago

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

Melon Von Harvard
9 months ago
Reply to  Andrey

at all times …

Timothy Mwirabua
8 years ago

Thanks!