Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DOS line endings to Linux line endings in Vim

If I open files I created in Windows, the lines all end with ^M. How do I delete these characters all at once?

like image 900
Bert Hekman Avatar asked Sep 17 '08 12:09

Bert Hekman


People also ask

How do you change DOS line breaks to Unix line breaks?

The simplest way to convert line breaks in a text file is to use the dos2unix tool. The command converts the file without saving it in the original format. If you want to save the original file, add the -b attribute before the file name.

How do I convert Windows line endings to Linux?

To convert from Windows to Linux line breaks you can use the tr command and simply remove the \r characters from the file. The -d option tells the tr command to delete a character, and '\r' specifies the character to delete. The input to tr is redirected from the file fileWindows.

What line endings does Linux use?

Back to line endings The reasons don't matter: Windows chose the CR/LF model, while Linux uses the \n model. So, when you create a file on one system and use it on the other, hilarity ensues.


2 Answers

dos2unix is a commandline utility that will do this, or :%s/^M//g will if you use Ctrl-v Ctrl-m to input the ^M, or you can :set ff=unix and Vim will do it for you.

There is documentation on the fileformat setting, and the Vim wiki has a comprehensive page on line ending conversions.

Alternately, if you move files back and forth a lot, you might not want to convert them, but rather to do :set ff=dos, so Vim will know it's a DOS file and use DOS conventions for line endings.

like image 84
pjz Avatar answered Sep 30 '22 10:09

pjz


Change the line endings in the view:

:e ++ff=dos :e ++ff=mac :e ++ff=unix 

This can also be used as saving operation (:w alone will not save using the line endings you see on screen):

:w ++ff=dos :w ++ff=mac :w ++ff=unix 

And you can use it from the command-line:

for file in *.cpp do      vi +':w ++ff=unix' +':q' "$file" done 
like image 43
Ludvig A. Norin Avatar answered Sep 30 '22 09:09

Ludvig A. Norin