Easy Recursive Find and Replace Using find and sed

When working with websites (especially when moving them from one server to another) you sometimes need to edit either all or at least many of the files that make up the site to change paths or connection strings (this is generally only a problem if the site is coded poorly and doesn’t allow for these to be set in a single file!).  Sometimes this action can require manually opening hundreds of files and looking for the lines that need to be edited.  This article is a brief tutorial which can save you hundreds of hours.

Changing database server hostnames/usernames/passwords etc.:

find . -type f -exec sed -i~ s/old text/new text/g {} \;

Sometimes you don’t need to replace part of a line, lets say you need to remove lines, maybe you about to hand over a perl powered website to somebody you really dont like and you want to remove all of your code comments!

find -type f -exec sed -i '/string/d' {} \;

Also, if your string contains the / character you will either need to use a different delimiter for sed or escape the character with \ when it appears in the string. For example to remove single line php comments:

find -type f -exec sed -i '/\/\//d' {} \;


find -type f -exec sed -i '_//_d' {} \;

As always, if you have any questions or even suggestions about this article drop me a line in the comments!

One thought on “Easy Recursive Find and Replace Using find and sed

Leave a Reply

Your email address will not be published. Required fields are marked *