Remove ^M from Files Using the vi Editor

By | February 25, 2015

After moving text files from Microsoft Windows to the UNIX environment, I frequently end up with the ^M characters at the end of each line in the files. This occurs because UNIX uses 0xA for the newline character, while Windows uses a combination of two characters: 0xD 0xA. 0xD is the carriage return character. The vi editor displays 0xD as ^M. The ^M characters do not hurt anything being there, and the files still execute fine despite having the extra characters, but I like my code clean, so I remove the characters whenever I notice them.

To globally remove all of the ^M characters in a file using the vi editor, issue the following vi command:

:%s/^M//g

To enter ^M, type Ctrl-v, then Ctrl-m. (hold down the Ctrl key then press v and m).

  • In UNIX, you can escape a control character by preceding it with a Ctrl-v.
  • The :%s is a basic search and replace command in vi. It tells vi to replace the regular expression between the first and second slashes (^M) with the text between the second and third slashes (nothing in this case).
  • The g at the end directs vi to search and replace globally (all occurrences).

Leave a Reply

Your email address will not be published. Required fields are marked *