Find and remove ^M (control+M) characters in unix
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
-
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)
- 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.
awesum post very helpful…..
thanks…
And one more thing, if you use dos2unix command then you get some error msg like "keyboard" just ignore that.