Linux/Unix Search and Replace Text from Multiple Files

In Linux/Unix, for newbie to do search text from multiple files/folder look like difficult, replacing string from file sound even harder. It’s actually not hard or complicated to search and replace text from multiple files in Unix/Linux. The key is what command to use, there will be two main commands involve in search and replace, which are find and sed

For example I am hosting multiple web applications, the development might have several pg_connect command to connect database, in the event I am migrating database to other IP address, it might be hard for them to dig the file and replace the IP Address with new IP Addresses.

In Linux/Unix, you can search through the directories, looking for the files and replace it with the new IP address. Here is the sample.

shell> find /path/to/dir/* -type f -exec sed -i .backup20100714 -e "s/host=x.x.x.x/host=y.y.y.y/g" {} \\;

The command above will search for files in the directory.
find -type f mean look for File only.
find -exec is to execute something from returned results.
sed -i means backup the files, in case you would like to restore later.
sed -e “s/host=x.x.x.x/host=y.y.y.y/g” is to replace x.x.x.x to y.y.y.y

You have backup files name filename.php.backup20100714, now what you need to do is move the files in a backup directory.

shell> find /path/to/dir/* -name "*.backup20100714" -exec mv {} /your/backup/dir/ \\;

You might want to explore on find command, it can do a lot of cool stuffs.