Search code examples
gitdiff

git diff show changes where surrounding lines contain search term


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 = "git@github.com: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.


Solution

  • 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 = git@github.com: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