We know that the SED command in Linux stands for stream editor and is mainly used to perform functions on files, and the functions usually are either searching for a word, or replacing it or insertion of something and few more. It is a very useful command and can be found on the Linux kernel.
It should also be noted that the BSD (Berkeley Software Distribution) sed shipped with the OS X does need the -i flag to work and the GNU one doesn’t.
One way to make the GNU version of the SED to work on the Mac OS X, is to directly install the gnu-sed along with the default names which will assure you that you won’t have to run different commands on both the operating systems.
In order to install the gnu-sed on the Mac OS X, you can consider the steps shown below.
brew install gnu-sed --with-default-names
This will install the gnu-sed and you can make use of it, the same way you use it in your other Linux machine.
A better solution is to make use of the command that is shown below which is the inplace replace command along with a file extension as the .bak which will help you in achieving the same command for both the Mac OS X and the GNU.
sed -i.bak ‘s/sample/new_sample’ filename
In the above command, the string in the single-quote means that we are replacing the word in a particular file to new_sample.
Now let’s first run the above command on GNU and see how the output turns out to be.
$ sed --version | head -1 GNU sed version 4.2.2 $ echo 'sample' > 1.txt $ sed -i.bak 's/sample/new_sample/' ./1.txt $ ls 1.txt 1.txt.bak $ cat ./1.txt new_sample
$ sed --version 2>&1 | head -1 sed: illegal option -- - $ echo 'sample' > 1.txt $ sed -i.bak 's/sample/new_sample/' ./1.txt $ ls 1.txt 1.txt.bak $ cat ./1.txt new_sample