Linux
22 October 2011 1 Comment

Expand Tabs to Spaces Recursively

If you have a bunch of files with tabs, and you want to replace these tabs with the appropriate amount of spaces then you can use the expand command.

$ expand --tabs=4 stuff.php > stuff.php

With the –tabs switch the tab width is denoted, in spaces. So in this example each tab is replaced with four spaces.

In order to run this command on all PHP files in a directory, including its subdirectories, use this script:

#!/bin/sh
#
# Iteratively replaces tabs in .php files with 4 spaces.
#
 
find . -name "*.php" | while read line
do
  expand --tabs=4 $line > $line.new
  mv $line.new $line
done

Save it to a file and execute it in the directory you want to run the expands:

// Create the file in the current directory
$ touch expand.sh
 
// Use a text-editor like 'nano' to put the script code in the file.
$ nano expand.sh
 
// Make the script executable
$ chmod +x expand.sh
 
// Run the script
$ ./expand.sh
Tags: , expand, , php, spaces, tabs

One Response to “Expand Tabs to Spaces Recursively”

  1. Luc 24 October 2011 at 8:16 am #

    Nice, this might come in handy some day..

    Reply