How to Do a MySQL Find and Replace on the Entire Database

Hey there! Some links on this page may be affiliate links which means that, if you choose to make a purchase, I may earn a small commission at no extra cost to you. I greatly appreciate your support!

It’s surprisingly easy to perform a find and replace on an entire MySQL database. With some command line magic and help from our good old friend sed, you can replace a string across every single table in your database.

No experience necessary. I’ll walk you though every step of the process.

MySQL Find and Replace

The easiest way to search and replace a string across all tables in a MySQL database is with mysqldump and sed. Please see the following example.

mysqldump mydatabase > db.sql
sed -i 's/stringtofind/stringtoreplace/g' db.sql
mysql mydatabase < db.sql

In the example above, we first dump our database named mydatabase into a file called db.sql.

Next, we use the sed command to replace stringtofind with stringtoreplace. The -i option to the sed command edits the file in place. Some implementations of sed like the Mac version don’t support the -i option. Instead, you can do something like sed 's/stringtofind/stringtoreplace/g' db.sql > tmp and then mv tmp db.sql to “manually edit in place” 🙂

Finally, we take our modified db.sql file and apply it back to the MySQL database. This will overwrite the entire database. If this scares you, don’t sweat it. You already have a copy of your database!

What About Slashes?

What if you need to find and replace a string with a slash like a URL? This might initially seem impossible since the sed command itself uses a forward slash as a delimiter to begin with.

Well, the cool thing about sed is that whatever character follows the leading s is the delimiter. In the example below, instead of a slash, we use a hashtag as our delimiter to find and replace a URL in our MySQL database.

sed -i 's#http:\/\/tonyflorida\.com#https:\/\/tonyflorida\.com#g' db.sql

Also notice how we escape the forward slashes in the URL with backward slashes. It’s not very pretty, but it gets the job done.

If you have any questions about replacing strings in your MySQL database, don’t hesitate to drop a line down below in the comments.

Facebook
Twitter
Pinterest
LinkedIn
Reddit

Meet Tony

Tony Teaches Tech headshot

With a strong background in computer science and enterprise web development, Tony is determined to demystify the web. Discover why Tony quit his job to pursue this mission. You can join the Tony Teaches Tech community here.

Leave a Reply

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