How to search and replace text in all php-files in a directory and it’s subdirectories

I am looking for a shell script that recursively traverses all .php files in a directory and performs a search & replace of a particular text pattern.

The search pattern is quite long ( > 5000 characters) so it might be saved in another textfile for convenience. Also it contains forward slash characters.

edit: i think i figured out the first part:

find . -name „*.php“

but then how do i search & replace in those files?
shell-script text-processing grep find ls
shareimprove this question
edited Jan 17 ’12 at 9:54
asked Jan 17 ’12 at 7:58


It can be done easily with a good combination of sed and xargs.

find . -name „*.php“ | xargs -n 1 echo

will show you the power of xargs.

After that, on a sample file, you can test the regexp, with an inplace change (-i) or a backup change (-i.bak). You can also use an other character to replace ‚/‘ if your pattern/replacement already have one.

At the end, it should looks like :

pattern=`cat /path/to/pattern`; replacement=`cat /path/to/replacement`
find . -name „*.php“ | xargs -n 1 sed -i -e ’s|$pattern|$replacement|g‘

edited Jan 17 ’12 at 10:16 Coren


ok thank you! same question here: how would i load the search pattern from a file?

– clamp Jan 17 ’12 at 9:52
something like this, maybe ? pattern=cat /path/to/pattern; replacement=cat /path/to/replacement; find . -name „*.php“ | xargs -n 1 sed -i -e „s/$pattern/$replacement/g“

– Coren Jan 17 ’12 at 10:04


thank you! the only problem remaining is that the pattern contains forward slashes which seem to be problematic in the regexp

– clamp Jan 17 ’12 at 10:06


you can use an other character than ‚/‘ in sed. For instance, sed -i -e „|$pattern|$replacement|g works well

– Coren Jan 17 ’12 at 10:15


thank you! now it runs without errors but it doesnt seem to replace anything. i guess the search pattern is not found. (although it is there). the search pattern contains all kind of characters including tabs, spaces, $, <, > etc. could that be the problem?

– clamp Jan 17 ’12 at 10:22


$ is used by bash for variables. you’ll need to escape it with a ‚\‘.

– Coren Jan 17 ’12 at 10:33