How to remove CONTROL-M characters from a file : Linux / Unix

Whenever we transfer the files from Windows to Linux / Unix system generally it has CONTROL-M character inside. Which appears as ^M inside the files . To prevent this you can first copy paste the content in notepad then again copy to file in linux system. Here, notepad will help you to transfer the ASCII character.

Steps to remove CONTROL-M characters from a file

To print CONTROL-M character (^M) – use your keyboard and press keys CTRL-V and CTRL-M . It will print the CONTROL-M Character exactly.

1. In vi / vim editor :

To remove CONTROL-M character inside file by using vi / vim editor , use the following command .
(a) Open the file with vi/vim editor
(b) Press ESC key
(c) Then type , :%s/^M//g and press enter. (Remember, to type ^M , press CTRL-V and CTRL-M keys from your keyboard.)

2. By using sed command :

Simply use the sed command in below given format. The command will edit the file. In case you only want to preview remove -e from given below command.

sed -e 's/^M//g' filename