Finding (and removing) ^M in files

I know I’m not the only person who works in multiple operating system environments, and gets ticked off when finding a ^M saved in the newline of text files or scripts.  Windows/MSDOS uses ‘\r\n’ and Unix/Linux/OSX uses ‘\n’ for newline at the code level, and we see the Windows \r as ^M.  An easy to way to work around this at the Linux/Unix/OSX level is rather simple.

To find files that have the ^M at the Linux/Unix/OSX prompt, type the following:
grep -r $’\r’ *
or for a single file
tr -d $’\r’ < filename

To remove all ^M in a file, type the following (replacing filename with the file in question):
sed $’s/\r//’ -i filename

I figured I’d share this since it’s something you don’t do all of the time, and it’s just one of those things.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s