When I am editing source files using Vim and other editors, sometimes I get these ^M
characters at the end of each line.
I think that it has something to do with editing a file on Windows and then on Linux.
How can I remove all of these automatically?
As a command, type
:%s/^M$//
(To get ^M, press ^V ^M, where ^ is CTRL on most keyboards)
:%s/\r$
–
Joo One easy way to strip out the DOS line endings is to use the ff
option:
:set ff=unix
:wq
Now your file is back to the good-old-Unix-way.
If you want to add the DOS line-endings (to keep a printer happy, or transfer files with Windows friends who don't have nice tools) you can go the opposite direction easily:
:set ff=dos
:wq
git diff
shows every line deleted and every line added :/ –
Chastitychasuble diff
, not on git
. –
Surreptitious You can do this:
:set fileformats=dos
It will hide the ^M
's, without touching the file.
There's a program called dos2unix that should strip those for you. Windows uses different line-ending characters which is why that happens.
This worked for me in a file that had everything on one line:
First find all matches
:%s/^M//
(To get ^M
, press ^V ^M, where ^ is Ctrl on most keyboards)
Then replace with newlines
:%s//\r/g
Combined command would be:
:%s/^M/\r/g
I tend to run afflicted files through fromdos
before reopening them. fromdos
is part of the tofrodos package.
The origin of the problem may have been through an FTP transfer. When you FTP these files from one box to another, make sure to use ASCII transfers. Use the command "ASC."
" put this in your ~/.vimrc file and :source ~/.vimrc
" then you can do: Dos2Unix
" dos2unix ^M
fun! Dos2unixFunction()
let _s=@/
let l = line(".")
let c = col(".")
try
set ff=unix
w!
"%s/\%x0d$//e
catch /E32:/
echo "Sorry, first save the file."
endtry
let @/=_s
call cursor(l, c)
endfun
com! Dos2Unix keepjumps call Dos2unixFunction()
My situation is, I was developing my project on Windows, later I ran a Linux virtual machine, and by sharing folders, I directly opened the project that was originally on Windows in the Linux virtual machine. When I ran git status
, a large number of files were listed, and each line of these files ended with ^M
. I solved this issue with the following two commands:
git status -s | grep "^ M" | awk '{print $2}' | xargs dos2unix
git status -s | grep "^ M" | awk '{print $2}' | xargs git add
:%s/\r$//
Should remove all carriage returns \r
(displayed as ^M
) at end of lines.
© 2022 - 2025 — McMap. All rights reserved.
^M
s. The only indication you have when editing a DOS text file in Vim is if you have%{&ff}
in yourstatusline
option value. Vim shows^M
when the line ending style is mixed. It means you've used a text editor that isn't as savvy as Vim, which hasn't followed the existing line ending style, as Vim will by default. If you use Vim or something else of its calibre on Windows, you won't get wrecked line endings like that. – Phenacaine