Changing line endings on Windows using Powershell and Git

Posted on

If you ever have had to work with a code base where files contain lines with inconsistent line endings


You would like to make sure that at least the files you have touched no longer have that problem


You use Powershell and MSysGit on Windows, you can use this:

To convert LF to CRLF:

git diff --cached --name-only | foreach { dos2unix -D $_ }

This is basically telling git to list the files that have been staged and iterate over them to change their line endings

That’s a fair amount of typing, so I’ve aliased the git command

git config --global alias.stgd 'diff --cached --name-only'

And the command now becomes:

git stgd | foreach { dos2unix -D $_}

Much nicer. However, the files are still not staged. Let’s take care of that:

git stgd | foreach { dos2unix -D $_; git add $_}

And that will make sure any staged files you’ve worked on have proper line endings on Windows 🙂

NOTE: I’m using dos2unix here and not TYPE unix_file | FIND "" /V > dos_file as suggested by wikipedia because find works differently in powershell.

Leave a Reply

Your email address will not be published.