Find and remove ^M (control+M) characters in unix

Published On: March 28th, 2012|Last Updated: January 7th, 2023|Categories: Web Design|Total Views: 7206|Daily Views: 1|
When the file is transferred from windows to Unix, we may find some ^M (CTRL+M) characters in the file, because windows operating system and Unix operating system save the end of line markers differently. Windows OS store it as a pair of characters as 0x0A0D and Unix will store as 0x0A. So the remaining 0D is displaying as ^M character in Unix. This may cause error when executing the file. So follow the below steps to find and remove the CTRL M characters completely from the file:

Commands

  1. To find ^M (control +M) characters in the file:

    For single file: $ grep ^M

    filename For Multiple files: $ grep ^M *

    (This command searches all the files in the current directory)

  2. To remove ^M (control +M) characters in the file:

    $ dos2unix filename filename

    (dos2unix is the command used to delete ^M characters in the file

    Find inside vi editor:

    Open the file in vi editor mode and type the below command:

    :%s/^V^M//g

    For ^V use (Ctrl + v) and for ^M use (Ctrl+m), after you type this, the command looks like this:

    :%s/^M//g

    This command search for the Control m (^M) character and replace with nothing.

Tips & Warnings

  • For transferring files like text files, shell scripts, dat files use ascii mode as it prevents file from getting ^M(control M) characters.
  • Press (Ctrl+v) + (Ctrl +m) – (hold Ctrl button and press v and m letter) to type ^M, not (caps+M)
  • In some cases, you need to use (Ctrl+v) + (Ctrl+v) + (Ctrl+m) to type ^M character.

3 Comments

  1. Avatar of abhishek pathak
    abhishek pathak Apr 6, 2013 at 1:14 pm - Reply

    awesum post very helpful…..

  2. Avatar of Ramya Love Ramya
    Ramya Love Ramya Aug 21, 2012 at 7:54 am - Reply

    thanks…

  3. Avatar of Amy Louise Jackson
    Amy Louise Jackson Apr 24, 2012 at 9:28 am - Reply

    And one more thing, if you use dos2unix command then you get some error msg like "keyboard" just ignore that.

Leave A Comment