vi/vim FAQ: How can I remove control-m
^M characters in a text file using vi or vim?
If you’ve ever opened a text file with vi (or vim) and saw a message on the bottom of the screen that says “dos” or “dos format”, there’s a reason for this. The file was probably created on a DOS or Windows computer, and it contains extra binary characters that are not normally found in a file created on a Unix or Linux system.
You can see this very easily by closing your current vi session, and then re-opening the file with vi, but also using the
-b command line argument, like this:
vi -b myfile.txt
-b indicates that you want to open the file in binary mode, and in this mode you can see a bunch of mysterious
^M characters at the end of each line. These are the extra characters that tell your Unix system that the file was created on a DOS system.
These extra characters are usually harmless, but some times they can lead to error messages, the most common error message being bad interpreter. You get the "bad interpreter" error message when there is a
^M character at the end of the first line of a script, like the first line of this Perl script:
#!/usr/bin/perl^M # # more code down here ... #
You’ll get the same error message with Linux shell scripts. The way to get rid of that “bad interpreter” error message is to get rid of that
^M character, which I’ll discuss next.
Getting rid of these pesky
^M characters is pretty easy. First, open the file with the
-b option, as shown earlier:
vi -b myfile.txt
Next, type the
: character, to put the vi editor in last-line mode.
Now enter the following command, but where you see the
^M character in that line, what you really need to type is this character sequence:
(That's “control v, control m”.)
Here’s the way this will look on the last line of your vi/vim edtitor:
Follow that with an
What this command means is, “From the first line of the file to the last line of the file, replace all
^M characters with nothing.”
If everything worked successfully you’ll see that all of those
^M characters are now gone.
Conversely, if you had some problems issuing that command, you can use the
u command to undo whatever changes may have been made, or issue this command to bail out of the vi editor without making any changes to your file: