We have two options here:
sed is a powerful stream editor although it also features a handy in-place/
-i flag that may modify the source file. Unfortunately this is a non-standard FreeBSD extension and therefore results in unportable code. Simply put, some systems may have it, some others may not.
ex on the other hand is a standard Unix command-based editor that is a better fit for these kind of tasks.
sed is also capable of creating a backup file prior to modifying the original source file.