Search and replace inside a MySQL database
Posted in mysql, tips on March 13th, 2010 by fseek – 3 CommentsHave you ever wanted to modify multiple rows and tables inside your MySQL database? We have a simple way to do it.
Well, yesterday I had to modify in one of our databases (a big one), every occurrence of an email address (contact@company.com) to another one (sales@company.com). Doing that via our web interface would take a long time, so I did the simple way:
1- Backup your MySQL database using Mysqldump
$ mysqldump -u dbuser -pdbpass dbname > dump.sql
Now we have our database backed up at dump.sql
2- Search and replace inside your MySQL dump
We did this very easily with sed to replace “contact” for “sales”. Just change for whatever values you want to replace.
$ cat dump.sql | sed ’s/contact@company/sales@company/gi’ > dump-fixed.sql
Note that we did a case insensitve search for contact@company.com and replace that with the sales address. Also, we used the “g” modifier to apply to all cases (not the first one in the line).
3- Restore your database using the modified dump
$ mysql -u dbuser -pdbpass dbname < dump-fixed.sql
Yes, it was that simple. No more running a bunch of INSERTS, DELETES, ALTER tables, etc…
