How to grep the git diff?

后端 未结 9 633
耶瑟儿~
耶瑟儿~ 2021-01-31 06:55

Is there a way to show the git-diff filtered by a given pattern.

Something like

git grepdiff pattern

changed file
+++ some sentence with pattern
change         


        
相关标签:
9条回答
  • 2021-01-31 07:34

    On Windows, a simple solution is:

    git diff -U0 | findstr string
    

    If you want grouping by filename, use this

    FOR /F "usebackq delims==" %i IN (`git diff --name-only`) do git diff -U0 %~fi | findstr string
    
    0 讨论(0)
  • 2021-01-31 07:39

    Here is a custom diff tool that allows grepping inside changes (but not the context):

    Usage

    GIT_EXTERNAL_DIFF="mydiff --grep foo" git diff

    This will output those lines in your changes that contain foo (including lines where foo disappeared because of your changes). Any grep pattern can be used instead of foo.

    Each output line starts with the following prefix:

    filename: oldlinenum: newlinenum|
    

    The script can also be used without the --grep option, in which case it simply formats the full diff (i.e. providing full context) as described above.

    mydiff

    #!/bin/bash
    
    my_diff()
    {
        diff --old-line-format="$1"':%6dn:      |-%L'     \
             --new-line-format="$1"':      :%6dn|+%L'     \
             --unchanged-line-format="$1"':%6dn:%6dn| %L' \
             $2 $3
    }
    
    if [[ $1 == '--grep' ]]
    then
        pattern="$2"
        shift 2
        my_diff "$1" "$2" "$5"|grep --color=never '^[^|]\+|[-+].\+'"$pattern"'.*'
    else
        my_diff "$1" "$2" "$5"
    fi
    
    exit 0
    
    0 讨论(0)
  • 2021-01-31 07:40

    This did the job for me, I hope it will help someone:

    git diff | grep  -P '^\+|^\-'
    
    0 讨论(0)
提交回复
热议问题