Removing Carriage return on Mac OS X using sed

Gaurav Fotedar picture Gaurav Fotedar · Feb 7, 2014 · Viewed 30.9k times · Source

On Linux for removing carriage return we can execute:

sed -i 's/\r//g' <file>

But the same will not work on Mac OS X. Need to prepend $ like:

sed -i $'s/\r//' <file>

And "g" is also not needed.

Why is this so?

Answer

anubhava picture anubhava · Feb 7, 2014

It is because sed available on OSX doesn't recognize \r as a special character unlike the sed on Linux does.

You can either use it the way you're using:

sed -i.bak $'s/\r//' file

OR this:

sed -i.bak "s/$(printf '\r')//" file

OR else you can use tr on OSX:

tr -d '\r' < file