Cleaning up Windows Line Endings in Vim

I have a file which has been edited in windows with an incorrect setting. All the lines have


At the end of each line.

To search for these in Vim, you can type ctrl+v (to mean “take my next key combination literally”) then ctrl+m. To clean up my file I used:

:% s/^M$//

Where the ^M is typed using Ctrl+V, Ctrl+M. I’ve recorded it as a macro as I seem to be fixing the same thing a lot these days. Hope that helps someone!

4 thoughts on “Cleaning up Windows Line Endings in Vim

  1. Vim should detect whether to use set fileformat=dos or fileformat=unix, unless the lines are not delimited consistently.

    I tend to use perl to make these kind of code changes, e.g.
    perl -pi -e ‘s/\r$// *.sql
    also pretty useful for any other global search/replace problems you might have.

    The svn:eol-style property in Subversion sounds promising. I wonder just how well it copes well inconsistent end of line delimiters – hopefully better than vim!

  2. Geoff: Its not vim’s fault!! I’ve deliberately got my vim set to expressly show these line endings – we develop for a linux platform so windows line endings are bad news and I like to be able to see them. I’m surprised to see you recommend perl’s regex over vim’s as my understanding is that the vim one is powerful. Certainly I haven’t needed anything it can’t do, and having the functionality right in the editor is very useful.

  3. I expect Vim uses PCRE so it should be on a par with Perl. But the “perl -pi” lets you search/replace multiple files without even firing up an editor. I use it for renaming variables, fixing problems caused by bad copy and paste etc.

    Using the svn:eol-style property should remove the need for any manual intervention. Haven’t tried it myself, but seems well worth looking into.

  4. Hehe, it wouldn’t occur to me to use perl for that (or indeed for anything!). I’d probably rummage around for find or awk in that scenario, although I still have a lot to learn about those two tools.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.