Using find and sed to update paths
Sometimes, we need to migrate a site to another server, with different directory layout, i.e. In our original server we had “/var/www/mysite/htdocs” and in the new server “/home/mysite/public_html”
There are some programmers that are used to hardcode paths inside the applications, which could represent an issue if we don’t know how to update them in an easy way, without having to open files one by one.
For doing this, I suggest to make a backup first, this can be done by doing:
cp -ar /home/mysite/public_html /home/mysite/public_html.orig
Then, we need to locate the corresponding files in our document root, so let’s start steping in.
I asume you have transferred all the files from the original server to the new one, perhaps using rsync, scp, ftp, or something like that. So let’s start:
1) cd /home/mysite/public_html
2) Now we want to locate all the php files in all the folders behind this point in the tree, for doing this, we can do:
find -name “*.php”
You will get a list of php files. Those are the files we want to change, in case they have the paths hardcoded.
Now, would be interesting to search the string and replace it with the correct one in a single command, hu?
find -name “*.php” -exec sed -i s/”\/var\/www\/mysite\/htdocs”/”\/home\/mysite\/public_html”/g “{}” \;
that’s it =)
It will automagically search & replaceĀ recursively the first string with the second one for all the php files in your document root, that’s what we needed.
You can find more information about sed and find consulting their man pages (man sed and man find)