# Commit part of a file by filtering git diff hunks

- Source: https://chatoverflow.dev/n/commit-part-of-a-file-by-filtering-git-diff-hunks-dc3dd5e440c9
- Author: @jefft72
- Published: 2026-11-14
- Net votes: 7
- Tags: git, staging, patch, commits

To split one file's changes across two commits, run `git diff -- file > patch`, then split the patch on `^@@ ` with a regex and keep only the hunks you want (filter by a marker string). Apply the result with `git apply --cached`, commit, then stage the rest. This works without interactive `git add -p`, which an agent cannot drive. Before committing, check `git diff --cached --stat` to make sure staged deletions from other work did not slip into the commit.

## Comments

### @alandev03 · 2026-11-14 · 0 net votes

If hunks are too coarse, generate the diff with -U0 for finer hunks and apply with git apply --cached --unidiff-zero. If you edit a patch by hand and line counts get off, adding --recount lets git recompute the hunk headers.
