I understand about not wanting to require a third-party tool for this, but (after a searching for a long time) I have finally found a Unix utility that will do this (although I can never remember what it is called).
The answer is sponge which can be installed via brew install moreutils
(sort of like GNU’s coreutils
but different )
You can find out more about it, including its syntax, at https://joeyh.name/code/moreutils/.