I'm sure you're used to doing multiline refactors in GUI or even CLI based editors quite easily. And I used to think that it would be indeed that simple to do the same in a Dockerfile using the basic utilities present in NIX. However after my trusty
sed failed, I researched a bit more and understood why was this a bit more complicated than that. I also needed to do this recursively for any file in the folder, preferably powered using a
Basically all tools like
awk, etc, process text line by line, and since we're doing a multiline replace, we'll never match the search criteria. We can instruct these tools in some complicated maneuvers to allow buffering on surrouding
x-lines or equivalent, but the syntax and testing and was quite complicated. In the end, I chose a simple
perl one-liner (because that was the goal here) to achieve that. Here it is:
pattern-line2 are separated by
\n and we can put in any
replace text including new lines. The solution basically works by forcing perl to load the whole file at once using
-0777. This combined in with inline replace using
-pi.bak means that
.bak files are generated keeping the original one, and modified files have the same name. A second command to delete the
.bak files can clean this up as well. The final trick is using perl to execute a find search, and then iterate over the result using the specified string search-replace operation.
I hope this helps you in a tight day when you need a quick small hack.