Vim Tips Wiki
Advertisement

Windows and Unix systems use different line delimiters for text files. Windows uses a carriage return followed by a new line, whereas Unix uses just a new line.

When you transfer a file from Windows to Unix the extra carriage return can cause problems.

Viewing the Extras Characters

In Vim, you can see the carriage returns by using binary mode, starting it with a -b command line option. The carriage returns will then show up as ^M at the end of each line.

Getting Rid of the Carriage Returns

There's some Unix utilities to remove the carriage returns, but you can do this in Vim, simply search for the carriage returns and replace them with nothing. The trick is entering the carriage return.

:%s/^V^M//g

^V should be entered by pressing and holding the Ctrl key and pressing V, ^M should be entered by pressing and holding the Ctrl key and pressing M. The ^V tells Vim to take the next character literally and not to interpret it, preventing the ^M from being taken as an Enter. You could also add a $ after the ^M to specify they should only occur at the end of the line but they really shouldn't be anywhere else.

Comments

The use of the :g command is not necessary, you can just use a :%s command.

Regardless, I don't think this tip adds anything to our current File format tip, and can probably be replaced by a redirect. I don't think that File format is very discoverable at the moment, if you're searching for a way to fix end-of-line characters but you don't know the root cause.

--Fritzophrenic 20:59, April 14, 2010 (UTC)

Advertisement