How to fix the “sed command expects \” error on Mac OS

April 7, 2021

If you are familiar with the sed command on Linux then you might be in for an unpleasant surprise the first time you try to use it on Mac OS.

Mac OS runs the BSD version of the sed command. As such, there are some syntax differences.

An example of a classic sed command, that is used in build scripts everywhere:

sed -i 's/WORD/REPLACEMENT' file.txt

If you run that command on Mac OS you will be very grumpily greeted with the error:

sed: 1: "file.txt": command expects \ followed by text

huh?

Oh right, this is the BSD version of sed.

You could fiddle with the command until you find something that works on Mac OS. Then you have to ensure it still works on your Linux machines as well.

Or, you could bypass the issue and install the GNU sed via Homebrew.

I choose the second option. It is easier and none of my build scripts will require changes. It can be installed with:

brew install gnu-sed

After install, there will be a new command called gsed. This is great, but still requires updating everything using sed. Simple fix, alias sed in your shell profile. I am still a bash user, so I edit ~/.bash_profile and add the line:

alias sed='gsed'

Source the profile file and voila, the familiar sed version has been restored for you on Mac OS!

Happy sedding.