Skip to content

Use the vi editor binary mode to remove control-m characters

by admin on July 2nd, 2009

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

The -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:

# more code down here ...

The way to get rid of that “bad interpreter” error message is to get rid of that ^M character, which I’ll discuss next.

Removing those ^M characters

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: [Ctrl]v [Ctrl]m

(That’s “control v, control m”.)

Here’s the sequence to type:


Follow that with an [Enter] keystroke.

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.

  1. gubi permalink

    Well… I am doing it quite differently.

    If I see DOS on the bottom of vi’s screen I just type:

    :set ff=unix

    No need for regexps or binary mode.
    It is good to know that there are other ways to do the same job.


  2. admin permalink

    Nice update 😛
    Thank you!

  3. Prasanth permalink

    Really Helpful Tip. Thanks

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS