Richard Holloway Blog

Replace tabs with spaces recursively

Posted in August 2012 by under developer

The easiest way to perform a find and replace across a large codebase is to use find and sed.

The find command allows you to specify exactly which files you wish to operate on, by name, modified date, owner and so on. Wrapping it in a for loop allows you to perform actions on each file.

In this simple example we want to replace tabs with four spaces in any file with the extension ".php" recursively within the current directory.

You will need to know that ^I ( typed by pressing Ctrl+V followed by Ctrl+I ) represents the tab character and . represents the current directory.

The command is

for phpfile in ` find . -name "*.php" -print `
do
  sed -i "s/^I/\ \ \ \ /g" $phpfile
done
            

Aside from find and replace, you could easily adapt this for other commands such as linting php files

for phpfile in ` find . -name "*.php" -print `
do
    php -l $phpfile
done