If I open files I created in Windows, the lines all end with ^M
. How do I delete these characters all at once?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With