10

I code Scala and it's convention is to use double spaces per level for identiation. But using different editors makes my sources filled with a mix of spaces and tabs.

I'd like to refactor all the files (*.scala files, actually, but specifying this is not necessary) (in a given directory and all the underlying FS branch (recursively)) automatically, replacing all the tabs with double spaces. I believe there is an easy and beautiful way to do this with classic Unix/GNU tools, but I lack any experience in this area. Would you be so kind to help me?

2 Answers 2

10

This should do it:

find . -type f -name '*.scala$' -exec sed -i 's/\t/  /g' {} +

Note: this is not tested.

5
  • 1
    This is not yet recursive. You can use find or a shell that supports **/*.scala for recursion.
    – janmoesen
    Oct 14, 2011 at 13:16
  • Edited to add recursive behaviour... Oct 14, 2011 at 13:23
  • Please do not promote find | xargs. Use find -exec instead, like I mentioned in my answer. Easier and safer.
    – janmoesen
    Oct 14, 2011 at 16:44
  • Tried this, no result. The command returns immediately and nothing changes inside the files.
    – Ivan
    Oct 25, 2011 at 0:30
  • this is not tested but the gist of it will work. Oct 25, 2011 at 7:23
9

Recursively, using expand (which was made for this purpose): find . -type f -name '*.scala' -exec bash -c 'for x in "$@"; do mv "$x"{,.bak} && expand -t 2 "$x.bak" > "$x" && rm "$x.bak"; done' {} +

I would do it with sed or perl (see Sardathrion's answer) because they support inline editing, but I wanted to mention good ol' expand anyway.

EDIT: That would be find . -type f -name '*.scala' -exec perl -p -i -e $'s/\t/ /g' {} +

2
  • The first variant works as expected. The second (perl) variant replaces a tab with only one space instead of two.
    – Ivan
    Oct 25, 2011 at 0:36
  • Yeah, sorry: that was a formatting mistake. The source code says two spaces, but the rendered HTML only shows one.
    – janmoesen
    Oct 25, 2011 at 6:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .