How to remove DOS linebreaks (^M) from files?

posted Sep 11, 2010, 6:24 AM by Sachchida Ojha

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.
Comments