threads / discuss / 62865

git diff -G: Regex pattern to exclude a word

Subject: git diff -G: Regex pattern to exclude a word

## tl;dr

2 messages between Jan 29, 2025 and Jan 29, 2025.

replies: 1people: 2as markdown or json

Raghavendra N· Jan 29, 2025, 06:05 UTC · lore
Dear Members,
TL;DR: Question is - How to use the -G option in git diff to exclude a word?

I'm trying to understand how the -G option in git diff works. Specifically I'm trying to test a Regex which excludes a word from the git diff.

Consider the following setup:
    > git diff
    first-file.txt
    @@ -1 +1 @@
    -Lorem Ipsum is simply dummy text.
    +Lorem Ipsum is simply dummy text. tree
    second-file.txt
    @@ -1 +1 @@
    -Lorem Ipsum is simply dummy text.
    +Lorem Ipsum is simply dummy text. ball

Word "tree" is added in the first-file.txt and word "ball" is added in the second-file.txt.

If I run this `git diff -G "^.*tree.*"`, it shows only the first-file.txt.
    > git diff -G "^.*tree.*"
    first-file.txt
    @@ -1 +1 @@
    -Lorem Ipsum is simply dummy text.
    +Lorem Ipsum is simply dummy text. tree

This is correct because the Regex is checking if textual diff has an added or a deleted line that includes a word "tree".

Now if I try to exclude the word "tree" with this Regex "^([^t]|(t[^r])|(tr[^e])|(tre[^e]))*($|(t($|(r($|e$)))))", it should only show the second-file.txt. But the diff lists both the files.

    > git diff -G "^([^t]|(t[^r])|(tr[^e])|(tre[^e]))*($|(t($|(r($|e$)))))"
    first-file.txt
    @@ -1 +1 @@
    -Lorem Ipsum is simply dummy text.
    +Lorem Ipsum is simply dummy text. tree
    second-file.txt
    @@ -1 +1 @@
    -Lorem Ipsum is simply dummy text.
    +Lorem Ipsum is simply dummy text. ball

So the question is how does the -G option work in this case? And how to use the -G option to exclude a word?

Thanks, Raghavendra

Chris Torek· Jan 29, 2025, 11:01 UTC · re: Raghavendra N · lore

Re: git diff -G: Regex pattern to exclude a word

On Tue, Jan 28, 2025 at 10:05 PM Raghavendra N <nraghavendra89@gmail.com> wrote:
> I'm trying to understand how the -G option in git diff works.
> Specifically I'm trying to test a Regex which excludes a word from the
> git diff.

"Inverting" a regular expression is technically always possible, but is difficult to get right, and I think you made a slight error in your attempt. See also https://www.vidarholen.net/contents/blog/?p=36 (which has a link to a Haskell program to generate an inverted regex automatically).

With `git grep` you can specify perl-style regular expressions, which allow negative lookahead, but `git diff -G` does not support that. See https://stackoverflow.com/questions/39789921/what-flavor-of-regex-does-git-use for details.

I think it would be nice to add some of `git grep`'s options to `git diff` here, but I leave that as an exercise. :-)

Chris

← back to recent threads