how to undo all whitespace changes with git

Viewed 9977

I have a git repo, where I replaced a lot of files locally.

git status now shows many many modified files.

Some are "really modified", others only differ by line endings.

I want the ones that differ only by line endings to go away (git reset them), but I cannot seem to find the linux-piping-foo to make it happen.

Bonus points for how to remove files whose only difference is the executable bit.

4 Answers

If you're allergic to bash and prefer powershell (formatting for clarity)...

git diff  --numstat --ignore-space-change --ignore-all-space 
          --ignore-blank-lines --ignore-cr-at-eol 
          --ignore-space-at-eol 
| % {($added,$deleted,$path)= $_.Split("`t"); 
    if ("$added$deleted" -eq "00") {$path} 
| % { git checkout HEAD $_}

Note that this is a pretty aggressive approach - the git options I've used here will also ignore added/deleted blank lines. Also remember that whitespace and even line-feeds can be semantically meaningful when in the middle of a string so use with that in mind.

It's possible that some of the git options are redundant but I've included them for paranoia's sake. You may wish to peruse the documentation to form your own interpretation.

Here's a slightly terser implementation for cutting and pasting...

git diff --numstat -b -w --ignore-blank-lines --ignore-cr-at-eol --ignore-space-at-eol | % {($a,$d,$p)= $_.Split("`t");if ("$a$d" -eq "00") {$p}| % { git checkout HEAD -- $_}

As was noted elsewhere, it may be advisable to take a copy of your changes before reverting by running git stash or copying to a backup folder first.

Related