An example of how to find and replace recursively using sed

I recently needed to find and replace a string of text inside a large text file.

The file was a database export from mysql (from a mysqldump command I had run).

And if you’ve ever run a mysqldump command you know those files can be pretty large / long.

It would be possible to move the file to your desktop, open it up in a text editor and do a find and replace, then move it back to the server. But large files take time to transfer and open up. And then you have to worry that did your text editor do something like add weird line endings to the file and will the file still work when it gets re-imported back to mysql?

So, why worry or do that when you have sed?

sed is a command line tool found in linux and let’s us modify text files (or more specifically “streams” of input).

In the below code example I am running a find command from the current directory (the “./”) and then telling find to run the sed command.

The sed command then looks at each file (the “{}”) that find picks up and in this case, replaces the string “olddomain.com” with “newdomain.com” (the “s” right before the “/”) all throughout that file. And it does that replacing “in-place” (the -i parameter) rather than printing the edited text to the console.

find ./ -type f -exec sed -i -e 's/olddomain.com/newdomain.com/g' {} \;

In my case, I was moving a WordPress website from one domain to another.

And actually, I ran the above code against the mysqldump file as well as the entire WordPress directory of files so that any reference to the domain would be found and replaced. Nice!

(WordPress likes to hardcode the domain being used into not only the database but also files, yuck)

However, I’m sure sed could be used for lots of other file or stream editing beyond WordPress migrations.

Happy sed-ing 🙂