I suggest you use the patch
utility for this purpose.
1. Create the patch file using a diff
command
Assuming you have two files, the one with the block you want to replace:
$ cat toreplace.txt
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
And the other one with the block you want to replace:
$ cat replacewith.txt
/* For the production version, the following codelines are commented
out
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
*/
You create a context diff between them and place the content to a patchfile:
$ diff -c toreplace.txt replacewith.txt > patchfile
$ cat patchfile
*** toreplace.txt 2024-03-17 12:12:31.073270945 +0200
--- replacewith.txt 2024-03-17 12:12:45.276887865 +0200
***************
*** 1,4 ****
--- 1,7 ----
+ /* For the production version, the following codelines are commented
+ out
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
+ */
2. Applying the patch
Now consider this is the original file:
$ cat myfile
line before 1
line before 2
line before 3
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
line after 1
line after 2
line after 3
You run the patch
command on the file you want to change using the patchfile
you've created before.
$ patch -cb myfile patchfile
patching file myfile
Hunk #1 succeeded at 4 (offset 3 lines).
- the
-c
flag to "Interpret the patch file as a context difference (the output of the utility diff when the -c
or -C
options are specified).".
- It isn't strictly required, because without it "The
patch
utility shall attempt to determine the type of the diff listing, unless overruled by a -c
, -e
, or -n
option."
- The
-b
option to " Save a copy of the original contents of each modified file, before the differences are applied, in a file of the same name with the suffix .orig
appended to it."
- You can remove this flag if you don't want to create a backup.
3. Validation
Now comparing the original file with the patched one:
$ diff -c myfile{.orig,}
*** myfile.orig 2024-03-17 13:00:24.936142831 +0200
--- myfile 2024-03-17 13:13:48.882669202 +0200
***************
*** 1,10 ****
--- 1,13 ----
line before 1
line before 2
line before 3
+ /* For the production version, the following codelines are commented
+ out
// Enable all errors
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(E_ALL);
+ */
line after 1
line after 2
line after 3