Recursive Sed

13 July, 2023 - Tags: sed, coreutils


TLDR

rg -l 'book.kubebuilder.io' | xargs sed -i 's/book.kubebuilder.io/notebook.kubebuilder.io/g'

You can also call this something like recursive sed and how you can work with it.

The problem that I was in hand is that I was working on a controller and I needed to change the domain of the controller. For example, let's consider the example domain book.kubebuilder.io and now you are asked to change this domain to notebook.kubebuilder.io How will you do that?

First I tried to do it manually using my editor but it was a lot of effort. I tried use utilities like sed which is used to substitution within a specific file. In this case, there were many files that were having this domain, all the types in /api folder, manifests in /config folder, controllers etc.

sed is simple if you want to work on a specific file but what if you want to work on multiple file using sed. You've to first get all those files and then use sed in combination with xargs

For listing the files I used ripgrep. ripgrep has a flag -l with which you can list all the files that have a particular word/pattern in it.

For listing all the files I used rg -l 'book.kubebuilder.io'

Now for substitution, I used the following.

rg -l 'book.kubebuilder.io' | xargs sed -i 's/book.kubebuilder.io/notebook.kubebuilder.io/g'