do not try to generate a patch file based on a text template.
That's almost like patching a patch file. It's not going to end well.
Of course, I just did exactly that, because I was dealing with a very specific case where dynamically generating a source code patch is somehow the most convenient option. It actually works, and the code could be worse, but setting it all up was not fun and I wouldn't recommend it.
(This is definitely a very common and normal programming problem to have in this decade. /s)