5.14. Using Patches

A patch file contains the differences between two versions of a file.

Create the following text file (with errors) and name it somefile.txt:

This is a sample file for testing "patch".

This paragraph has some intentional errrors.  They will be
cs easy as 321 to correct.

They will be corrected using a patch.

Make a copy of the file and name it somefile.orig:

% cp somefile.txt somefile.orig

Edit the somefile.txt and correct the errors so that it appears as:

This is a sample file for testing "patch".

This paragraph has some intentional errors.  They will be
as easy as 123 to correct.

They will be corrected using a patch.

We can now create a patch and display it to stdout:

% diff -ruN somefile.orig somefile.txt
--- somefile.orig       Thu Apr  8 14:04:37 2004
+++ somefile.txt        Thu Apr  8 14:05:11 2004
@@ -1,6 +1,6 @@
 This is a sample file for testing "patch".
 
-This paragraph has some intentional errrors.  They will be
-cs easy as 321 to correct.
+This paragraph has some intentional errors.  They will be
+as easy as 123 to correct.
 
 They will be corrected using a patch.

Typically, the patch is stored in some file:

% diff -ruN somefile.orig somefile.txt > somefile.patch

Restore the original file:

% mv somefile.orig somefile.txt

You can check the somefile.txt and verify that it is the original text with errors by cat somefile.txt. To apply the new patch:

% patch < somefile.patch
Hmm...  Looks like a unified diff to me...
The text leading up to this was:
--------------------------
|--- somefile.orig      Thu Apr  8 14:04:37 2004
|+++ somefile.txt       Thu Apr  8 14:05:11 2004
--------------------------
Patching file somefile.txt using Plan A...
Hunk #1 succeeded at 1.
done

The patch succeeded and created a backup named somefile.txt.orig. Verify that the contents of somefile.txt were changed using cat or your text editor.