How to remove the ^M characters in a file on FreeBSD?

How to remove the ^M characters in a file on FreeBSD?

This is simple:

There are multiple ways to do it. One is actually included in the FreeBSD-tips file:

tr -d \\r < file > newfile
— Originally by Dru

So if you installed the “games” distribution, you get tips every time you log in. And once in a while the above tip will show up.

I had never used that one however, I had always used this one (which I modified) that I found here:

sed -i.bak ‘s/^M$//’ filename # in bash/tcsh, press Ctrl-V then Ctrl-M

However, this one works with the sh, tcsh and bash but not with the csh shell.

This one worked on csh but I am not sure if it is recommended as it assumes every line ends with ^M.

sed -i.bak ‘s/.$//’ filename # assumes that all lines end with CR/LF

Anyway, I like how FreeBSD supports the -i parameter. Because if I am doing lots of files, I can have a script that does each file in a directory and then (of course I have a back up just in case) I can run sed -i.bak ‘s/.$//’ filename on each file and then do delete all .bak files so every file “appears to be” edited in place.


  1. Kayden says:

    Your penning method is pleasing and also the way you managed the topic with grace is commdneable. I am intrigued, I presume you are an professional on this subject. I just sign up for your RSS feed.

  2. Rizo says:

    For vi editor users: `:% s/^M//g`, (note: to get `^M` use ^V + ^M combination, where `^` is the Ctrl key).

Leave a Reply

How to post code in comments?