Applying a Patch That Removes Lines
Understand how to apply a unified diff that removes lines from a file. Covers '-' line prefixes, hunk counting, and how removal affects line numbering.
Basic Patches
Detailed Explanation
Removing Lines with a Unified Diff Patch
When a patch removes lines, those lines appear prefixed with - in the diff. The patch engine matches the removed lines against the original text and deletes them from the output.
Example Original
import React from 'react';
import PropTypes from 'prop-types';
import lodash from 'lodash';
function App() {
return <div>Hello</div>;
}
Example Patch
--- a/App.js
+++ b/App.js
@@ -1,7 +1,5 @@
import React from 'react';
-import PropTypes from 'prop-types';
-import lodash from 'lodash';
function App() {
return <div>Hello</div>;
}
Hunk Header Breakdown
@@ -1,7 +1,5 @@ means:
- The original has 7 lines starting at line 1
- The result will have 5 lines starting at line 1
- Net change: 2 lines removed
How Removal Works Internally
The patch engine walks through each line in the hunk:
- Context lines (
prefix) — kept in the output, must match the original - Removed lines (
-prefix) — must match the original but are not written to the output - Added lines (
+prefix) — written to the output (none in this example)
If a - line does not match the corresponding original line, the hunk fails to apply and the tool reports a context mismatch error.
Use Case
A security audit identified that your project imports unused dependencies. You receive a patch that removes these imports. Apply it to clean up the codebase without manual editing.