Git trick: Cleanup end-of-line changes

June 30, 2012

I was working on a site recently that was moved from one VPS hoster to another, and the ops team that moved it somehow introduced an end-of-line change to every file. I didn’t want to commit these junk changes, so I wrote this little snippet to clean them. For each modified file (not new ones), it counts the number of changed lines, excluding EOL changes, and if there are none, it checks out a clean copy of the file:

git st --porcelain | grep -r "^ M" | awk '{ print $2 }' | while read FILE; do
  LINES=`git diff --ignore-space-at-eol "$FILE" | wc -l`;
  if [[ "$LINES" -eq "0" ]]; then
    git checkout "$FILE"; 
    echo "$FILE"; 
  fi;
done