Remove CTRL-M characters from a file in UNIX

Description
How to remove CTRL-M characters from a file in UNIX.

You may need to do this when you import a text file from MS-DOS (or MS-Windows), and forget to transfer it in ASCII or text mode. Here are several ways to do it; pick the one you are most comfortable with.

  • The easiest way is probably to use the stream editor sed to remove the ^M characters. Type this command: % sed -e "s/^M//" filename > newfilename
    To enter ^M, type CTRL-V, then CTRL-M. That is, hold down the CTRL key then press V and M in succession.
  • You can also do it in vi: % vi filename
    Inside vi [in ESC mode] type: :%s/^M//g
    To enter ^M, type CTRL-V, then CTRL-M. That is, hold down the CTRL key then press V and M in succession.
  • You can also do it inside Emacs. To do so, follow these steps:
    1. Go to the beginning of the document
    2. Type: M-x replace-string RET C-q C-m RET RET
      where "RET" means <press the return key> and C-q and C-m mean <hold the CTRL key and press the m (or q) key>.