Replacing all those stupid tabs

Friday, February 26, 2010

I joined an existing project in my company a week ago, and was very annoyed when I saw tabs and spaces mixed all over the project. After we merged everything together, I took some time today to get all those tabs expanded to spaces. As this is not completly trivial, I wanted to post to code so I don't have to remember it later:
for file in `
  find . -path '*/.svn' -prune -o -type f -print
  | grep -v "\.\(gif\|jpg\|png\|ico\|ttf\)"
`;
do
    expand -t4 $file > /tmp/expand.tmp;
    cp /tmp/expand.tmp $file;
done;
rm -f /tmp/expand.tmp;
This snipped will find all files which are not withing .svn directories, and also exclude common binary files which should not be expanded. Those files are then converted with the expand command, stored to a temporary file and then copied back to the original location. The reason for that indirect way is because you can't pipe the output to the file which you are currently reading.

Comments to this article

  • Avatar of mikaelkael Reply mikaelkael Friday, February 26, 2010 2:36 PM

    Also possible with:
    find . -path '*/.svn' -prune -o -type f -print0 | grep -v "\.\(gif\|jpg\|png\|ico\|ttf\)" | xargs -0 sed --regexp-extended --in-place 's/\t/ /g'

    But not tested ;)

    • Avatar of Ben Scholzen 'DASPRiD' Reply Ben Scholzen 'DASPRiD' Friday, February 26, 2010 3:41 PM

      Not exacly, since the expand command takes care of tab-stops, which sed won't. That is the reason why this command exists ;)

      • Avatar of mikaelkael Reply mikaelkael Friday, February 26, 2010 4:07 PM

        I never needed it before, there are always things to learn :)

  • Avatar of Sebastian Reply Sebastian Friday, February 26, 2010 6:22 PM

    Good to know. Thx for the snippet!

  • Avatar of EllisGL Reply EllisGL Tuesday, March 2, 2010 3:18 AM

    Down with Tabs!!!

  • Avatar of Jared Reply Jared Friday, March 5, 2010 11:53 PM

    Why the hate on tabs? I agree on picking one or the other but at least with tabs if I want 2 spaces per indentation but you wanted 4 it would be an IDE setting...

Leave a comment

Please note that your email address will not be shown, it is only used to fetch your avatar image from gravatar.com and for notifications.

   _                             
  (_) _____  ___   _ _ __   __ _ 
  | |/ _ \ \/ / | | | '_ \ / _` |
  | | (_) >  <| |_| | |_) | (_| |
 _/ |\___/_/\_\\__,_| .__/ \__,_|
|__/                |_|