Deleting “^M” characters from your text file

Today I’ve downloaded a text file and I’ve found a lot of CTRL+M (15 octal character) garbage characters. This could be caused by a mistake when downloading the file with FTP bin mode enabled… who knows…

Anyway, our friend the tr command is here to help…

tr, as the man page tells, translates or deletes characters. If you want to delete those characters try this:

tr -d ‘\15′ < annoying_file.txt > clean_file.txt

Be careful! The above command will delete the CTRL+M characters. It’s better to substitute them by line breaks:

tr ‘\15′ ‘\12′ < annoying_file.txt > clean_file.txt

If you want to delete the original file…

tr ‘\15′ ‘\12′ < annoying_file.txt > clean_file.txt && rm annoying_file.txt

5 Responses to “Deleting “^M” characters from your text file”

  1. anonymous says:

    If you’re converting from DOS to UNIX:

    perl -p -i -e ‘s/(?< !r)n$/rn/'

    Or the reverse

    perl -pi -e ‘s/rn$/n/’

  2. morpheo says:

    Well, it could also be done with the vi editor, something like this:

    :%s/^M//g

    ^M character is represented by typing CTRL-V and CTRL-M.

    Regards.

  3. anonymous says:

    The ^M characters showed up in some of our .inc files and caused all kinds of display issues. To fix them, in a telnet session, I ran “dos2unix filename” on them and repromoted to the prodcution server. It took them out and the pages displayed correctly

    Ex.

    dos2unix default.inc

  4. anonymous says:

    The ^M characters are nothing but carriage-return characters denoted by \r that forms a part of the newline \r\n in DOS .
    Unix uses only \n as new line

    Like someone mentioned, in vi, they can removed by

    :%s/\r//g

    Regards,
    venks

  5. anonymous says:

    sorry, there should be a backslash before the ‘r’

    venks

Leave a Reply

You must be logged in to post a comment.