Removing ^M Characters from Your Unix Text Files

The files you just uploaded to your server are a mess. The original author used a Windows machine and now they all look like this:

#header div {^M
padding-top: 50px;^M
}^M
#header div a {^M
font-size: 24px;^M
color: #fdfdfd;^M
font-weight: bold;^M

...and so on. If you're like me you've found a few hundred Perl scripts to do this. I don't know why, but I was never a fan of that method. So without further ado, I would like to introduce you to another candidate: the "tr" command, or the translate command. tr takes characters from the standard input stream, processes them, and the writes to the standard output. This means we can use all our favorite Linux/BSD command and just pipe and redirect our way to results.

Using tr's -d (delete) option we can simply tell tr that we're wishing to delete any occurrence of "\r" which is being displayed as ^M in your files. Here's the super-simple command, using our old friend cat:

# cat file | tr -d "\r" > newfile

So have fun, and remember, if you're sending these files up using FTP you can skip this step by doing an ASCII upload instead of a binary upload.

  • Share/Bookmark