git tip: stage lines matching a regular expression

Have you ever wanted to make a big refactoring but realize now you’ve done too much for a single git commit?

What if there was a way to stage only the modifications that matched a regex (regular expression) somehow?

There is!

Use grepdiff. Install it from homebrew or macports. Use it to grep through the output of `git diff`.

First, preflight your regex to make sure it’s working:

git diff -U0 | grepdiff -E 'some[Pp]attern' --output-matching=hunk

Once it’s working well, pipe it to git to make it stage those lines:

git diff -U0 | grepdiff -E 'some[Pp]attern' --output-matching=hunk | git apply --cached --unidiff-zero

Then commit.

git commit -m "Rename the field somepattern to somePattern"<br>

Leave a Reply

Your email address will not be published. Required fields are marked *