Update July 2022: I have a really robust wrapper tool, rgr, which stands for "RipGrep Replace" and which wraps the incredibly fast RipGrep tool (rg), which you should use instead. See my other answer here. My wrapper supports all rg options, while adding -R for actual, on-disk text replacements.
Here I use grep to tell if it is going to change a file (so I can count the number of lines changed, and replacements made, to output at the end), then I use sed to actually change the file. Notice the single line of sed usage at the very end of the Bash function below: