How to search and replace text in multiple files in linux

Here's how to replace a string of text in multiple files under a specific directory and all it's sub directories.

cd /to/directory/containing/files
find . -name '*.php' | xargs perl -pi -e "s/OLDSTRING/'NEWSTRING'/g;"

Real world example:

Let's say we want to replace the following in every .php file:

'profile', 'load_profile'

with new string


Hence, we do the following...

cd /home
find ./ -name '*.php' | xargs perl -pi -e "s/'profile', 'load_profile'/'profile_load_profile'/g;"

Or you can do this using sed. The following will search and replace the content of every file within the specific directory you're in:

cd /to/directory/containing/files
find ./ -type f -exec sed -i 's/OLDSTRING/NEWSTRING/' {} \;

You can read the sed full documentation here.

Tags: linux admin php