Technology TidBits

Answers to various technical questions on php programming, mysql, linux, and many more categories.
25% off Hosting at HostGator.com:
Use Code techbits25



How can I remove DOS linebreaks (^M) from my files?

Last updated: 07/03/2009

Oh, the dreaded ^M - these usually occur when uploading files from a windows system, using ascii mode.  Some Windows editors may add the character to the end of each line as well during editing.

Sometimes, it's hard to even find them.  One pretty foolproof way on a Linux / Unix system is to use cat:

cat -e [filename]

This will show you lines with a $ at the end, and ^M's should show up, if they are there.  Here are a few options to remove them:

Method 1:

    In the vi editor, do the following:

    :.,$s/(ctrl-v)(ctrl-m)//g (enter)

    After typing the (ctrl-v)(ctrl-m) combination, you should see a "^M" in the line (note, the ^M is NOT just a '^' and an 'M', it's a special control character. If you try to reproduce it without the control sequence I describe here, you'll really mess up your file.

    By the way, if you do screw something up, just type:

    :q!

    which will exit the editor without saving, and you can start fresh and try again.

Method 2: Using sed

    From your Linux shell prompt, do the following:

    sed -e 's/(cntrl-v)(cntrl-m)//g' [filename] > [new filename]

    This creates a new file with the ^M's removed

Method 3:

    If your system has the 'dos2unix' utility, you can do this:

    dos2unix [filename]

    This has the advantage of replacing the original file, so you don't need to move anything after running this command.
blog comments powered by Disqus
Have your own Tech-bit to contribute? Submit it here

Other questions in this category:
How can I find out what is taking up all the space on my Linux server?
How can I use 'find' to execute commands on all files found?
How do I figure out how many processors and the speeds, etc. are in my Linux box?
How can I mirror / backup a set of files via ncftp?
My hostname keeps reverting to localhost (or localhost.localdomain) - how can I permanently fix this?
How can I determine if iptables is blocking traffic to my site?
Why does my ftp file listing stop at 2000 files?
How can I relocate files from a tar archive with extracting the files?
How can I get a list of files most recently updated / edited?
Some find examples for excluding a directory, and executing commands
Useful script to track spammers connecting to your server
How can I turn off / view my linux firewall using iptables?
How can I split a bit tar file into multiple small files?
How can I exclude some files / directories from a tar file?



Powered by KnowledgebasePublisher 1.1
Host Gator
Content provided by Roberts WebForge, Inc.