Is there a way to add all hunks in a file matching a regex?
I know I can search for a given hunk with /, but that only finds the first. I want to add all matching.
The following one-liner worked for me where <regex>
is a POSIX Extended Regular Expression. This requires grepdiff but it was already included in my Ubuntu distribution.
git diff -U1 -G<regex> --pickaxe-regex \
| grepdiff -E <regex> --output-matching=hunk \
| git apply --cached
The first line shows all differences whose patch text contains added/removed lines that match <regex>
. The problem is that this works on a file-level. That means that any changes in a file with at least one matching hunk will be included.
Thus we need line two. From all the hunks it receives grepdiff
will only print those that include a match for <regex>
. the problem here is, that it will not only match the lines that have actually been changed, but also the diff context. That's why the diff context is minimized¹ by passing -U1
to git diff
.
Finally line three takes the filtered diff and applies it to the index, e.g. stages it.
All in all this means that there are edge cases where this will add more than desired. But those can probably avoided by tweaking the regex a bit.
Thanks to @VonC for providing the link to that other SO question. It had all the pieces, they just had to be put together appropriately.
¹: You can also pass -U0
to omit the context altogether. While that completely removes the need for the pre-filtering in line one, the resulting patch won't apply anymore in line three.
Sadly, the patch in July 2011 went nowhere for now.
It would have introduced a git add --hunks=magic
option.
For now, you will have to do with:
git add
git stash pop
)Quite a cumbersome process.
Adding to the answer of @raphinesse and comments by @rubystallion, in addition to tips on how to format it from here, I made a git function to do this with the regex as the only input. Just enter this into your gitconfig (I used my global gitconfig) and use it with git regexadd <regex>
.
[alias]
regexadd = "!f() { git diff -U0 \
| grepdiff -E $1 --output-matching=hunk \
| git apply --cached --unidiff-zero; }; f"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With