Detabifying

Aug 17, 2006

If that was a word I'm not sure that would be the way to spell it. I'm referring to the process of replacing tabs by spaces.

The unix command expand does this job - taking a file and replacing tabs with a specified number of spaces.

What's the best way to run this command over a number files? find is likely to be useful here to return the files to process. In my case these are all .php and .css files in and below the current directory:

find . -name '*.php' -o -name '*.css'

will get me a list of these.

I thought perhaps I could use find's -exec option to run expand on the resulting files. Unfortunately expand will only send its output to stdout and as far as I can see there's no way of specifying that you want the output of an -exec'd command redirected.

However, I can iterate over the results with for and this does the trick (copying the results to /tmp/x in this case):
cp -r . /tmp/x
for f in `find . -name '*.php' -o -name '*.css'`; do expand -i -t4 $f > /tmp/x/$f; done

The initial cp is just a crude way of creating the directory structure in the destintion location to stop expand failing when sub-directories don't exist.