git diff show changes where surrounding lines contain search term

27 views Asked by At

For my Swift project, I'm trying to identify changes in the project.pbxproj file that have a particular word or regex in the surrounding context lines (not within the actual diff changes).

I've tried to use

git diff -G"<searchterm>"

But this seems to only apply the regex to the changes in the diff, not the surrounding context lines.

Tried also:

git diff -U# -G"<searchterm>"

but this doesn't alter the searchable lines.

example:

targeted diff looks like:

repositoryURL = "[email protected]:myRepo.git"
    requirement = {
-   branch = main;
-   kind = branch;
+   kind = upToNextMajorVersion;
+   minimumVersion = 1.0.0;
    };
};

running git diff -G"kind" or git diff -G"branch" will return a success, but git diff -G"repositoryURL" does not.

1

There are 1 answers

0
Tri10byte On BEST ANSWER

I would use grep and not try to leverage gits search for this.

Something like git diff | grep -A 5 myRepo

In your example would produce:

repositoryURL = [email protected]:myRepo.git
    requirement = {
-   branch = main;
-   kind = branch;
+   kind = upToNextMajorVersion;
+   minimumVersion = 1.0.0;

For context control in grep, from the man page:

       -A NUM, --after-context=NUM
              Print NUM lines of trailing context after matching lines.
              Places a line containing a group separator (--) between
              contiguous groups of matches.  With the -o or
              --only-matching option, this has no effect and a warning
              is given.

       -B NUM, --before-context=NUM
              Print NUM lines of leading context before matching lines.
              Places a line containing a group separator (--) between
              contiguous groups of matches.  With the -o or
              --only-matching option, this has no effect and a warning
              is given.

       -C NUM, -NUM, --context=NUM
              Print NUM lines of output context.  Places a line
              containing a group separator (--) between contiguous
              groups of matches.  With the -o or --only-matching option,
              this has no effect and a warning is given.

https://www.man7.org/linux/man-pages/man1/grep.1.html