Applying a Patch That Adds New Lines
Learn how to apply a unified diff patch that adds new lines to a file. Covers the basics of '+' lines, hunk headers, and context lines in unified diff format.
Detailed Explanation
Adding Lines with a Unified Diff Patch
The simplest patch operation is adding new lines to an existing file. In unified diff format, added lines are prefixed with +, while unchanged context lines are prefixed with a space.
Example Original
line 1
line 2
line 3
Example Patch
--- a/file.txt
+++ b/file.txt
@@ -1,3 +1,5 @@
line 1
+line 1.5
line 2
line 3
+line 4
How It Works
The hunk header @@ -1,3 +1,5 @@ tells us:
| Part | Meaning |
|---|---|
-1,3 |
The original file starts at line 1 and spans 3 lines |
+1,5 |
The new file starts at line 1 and spans 5 lines |
Lines starting with (space) are context lines — they must match the original text exactly. The patch engine uses them to verify it is applying changes to the right location. Lines starting with + are additions — they will be inserted at that position in the output.
Context Line Importance
Context lines serve as anchors. If the original file has been modified since the patch was created, the context lines help the patch engine locate the correct position. Most tools provide 3 lines of context above and below each change by default, matching the diff -u default.
Use Case
You received a code review patch from a colleague that adds new helper functions to a module. Rather than manually editing the file, paste the original and the patch to apply it instantly.