Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 8 down vote accepted

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' {} +

share|improve this answer
The first variant works as expected. The second (perl) variant replaces a tab with only one space instead of two. – Ivan Oct 25 '11 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 '11 at 6:26

This should do it:

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

Note: this is not tested.

share|improve this answer
This is not yet recursive. You can use find or a shell that supports **/*.scala for recursion. – janmoesen Oct 14 '11 at 13:16
Edited to add recursive behaviour... – Sardathrion Oct 14 '11 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 '11 at 16:44
Tried this, no result. The command returns immediately and nothing changes inside the files. – Ivan Oct 25 '11 at 0:30
this is not tested but the gist of it will work. – Sardathrion Oct 25 '11 at 7:23

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.