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
you can also just supply an empty string instead of ‘.bak’ to save no backup according to the man page
Thanks a lot !!!
Thanks! You saved my day! Stupid MacOS :/
Thanks!
brew install gnu-sed
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.
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
Thanks! What would we do without the internet at times..
at all times …
Thanks!
Thank you man! Also if we don’t need backup file – we can execute sed -i ”
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:
GREAT, Exactly what i needed. Works on mac as well btw ?