DEV Community

ᴙɘɘᴙgYmɘᴙɘj
ᴙɘɘᴙgYmɘᴙɘj

Posted on

2 1

Find and Replace a Bunch

Reposted from original article

Say I'm writing a journal and want to make sure I'm not leaking names. I'd like to change it consistently so it's anonymous, but still makes sense.

Instead of this

John force-pushed to `master` for some reason.  Harold didn't pull before he
added his fix and Betty ended up cherry-picking into yet another branch.  To
avoid this, next time we could...
Enter fullscreen mode Exit fullscreen mode

I'd like this

Farmboy force-pushed to `master` for some reason.  Jimmybob didn't pull before
he added his fix and Horsenator ended up cherry-picking into yet another
branch.  To avoid this, next time we could...
Enter fullscreen mode Exit fullscreen mode

Find-and-replace is what I want to do, but consistently and repeatedly (and quickly!). sed is the tool for the job.

First, define the replacements in files named encode and decode.

Encode

s/Betty/Horsenator/g
s/Harold/Jimmybob/g
s/John/Farmboy/g
Enter fullscreen mode Exit fullscreen mode

Decode

s/Horsenator/Betty/g
s/Jimmybob/Harold/g
s/Farmboy/John/g
Enter fullscreen mode Exit fullscreen mode

Replace

Then to replace, we use one of

sed -i "" -f encode journal.md
sed -i "" -f decode journal.md
Enter fullscreen mode Exit fullscreen mode

Obviously, we don't want to keep the encode/decode files with the output, but you get the idea. You can also send a whole bunch of files through sed with this set up. Maybe you could add a build step that cleans up content or something.

This article gives explains a few more basic sed options that may help you get started.

You can find an example here to play with.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (2)

Collapse
 
moopet profile image
Ben Sinclair

Note that sed you're using is BSD-style. On GNU, it'll still work (probably) but throw an error because the -i flag doesn't take a filename.

Collapse
 
reergymerej profile image
ᴙɘɘᴙgYmɘᴙɘj

Good point!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more