Using vi editor to remove ^M

Sometimes, when you open a file under Linux that was originaly created in Windows OS, special characters like ^M appear here and there. You can try the following solution on your vi editor to clear up those junk characters.


Open the file in your vi editor (for example file name : file-name.txt)


  • # vi file-name.txt


Hit “Esc” and type


  • :set ff=unix

Now save and exit from the file using


  • :wq!

Try open that file once again and look for those junk characters, it should be gone now. You can also use the dos2unix tool to fix it for large sized files.

Use the stream editor sed to remove it.

  • sed -e “s/\^M//” filename > newfilename
    Note: To enter ^M, type CTRL-V + M. That is, hold down the CTRL key then press V and M in succession.