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

3
4729
[dropcap]W[/dropcap]hen 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. 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. 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

LEAVE A REPLY