How to patch a file


This post goes over how to patch a file in the command line.

Prerequisites

Given you have file.old:

echo 'This is an old file.' > file.old

And file.new:

echo 'This is a new file.' > file.new

Diff

Create a patch:

diff -u file.old file.new > patch.diff

See patch.diff:

--- file.old	2025-02-25 22:22:22
+++ file.new	2025-02-25 22:22:42
@@ -1 +1 @@
-This is an old file.
+This is a new file.

Patch

Apply a patch:

patch < patch.diff # patch file.old < patch.diff

file.old becomes:

This is a new file.

Reverse a patch:

patch -R < patch.diff # patch -R file.old < patch.diff

file.old becomes:

This is an old file.

Apply a patch without reversing or creating a reject:

patch -NC < patch.diff # patch -NC file.old < patch.diff


Please support this site and join our Discord!