Replacing text in multiple files with sed

Josh Sherman
2 min read
Command-line Interface

My buddy Justin FINALLY got his website back up and running after “accidentally” letting his domain lapse.

On a new domain, of freaking course, which unlocked a task on my TODO list as I needed to update a bunch of broken links on my site to point to his new domain.

Since I’ve been trying to become more fluent with sed, that’s what I grabbed from my command-line toolbox to make short work of the task (and to fuel this post ;)

Because my site is version controlled, I wasn’t so concerned with backing up my files, but will do so for the sake of example and because I hate when people comment to let me know I fucked up something because they didn’t realize what they were running.

What I discovered when trying to update all of my posts is that sed expects an input file. My first pass I tried passing in the name of the directory and that was a no go.

To get sed to handle multiple files, instead of passing it a directory, you can pass it a glob for your files. In my case, I wanted to update all of the markdown files in my _posts directory:

sed --in-place='.bak' -- 's/justindavis.co/justindav.is/g' _posts/**/*.md

Omit the ='.bak' part of --in-place if you don’t want or need backups. Because I version control my site, it would be easy enough for me to revert if I borked something.

As it turns out, everything was fine, except in at one place I had a typo where I had .com for the domain instead of .co which given the above replacement, turned the TLD into .ism.

Easy enough, I just ran another sed to go ahead and clean that up as well.

Even with everything shored up, I still have a problem. Dude’s still not even running on HTTPS which is not only embarrassing for me as his friend, but also means I’m going to have to update all of the links yet again in the future once I finally shame him enough to fix it!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles