How to grep the git diff?

后端 未结 9 661
耶瑟儿~
耶瑟儿~ 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: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
    

提交回复
热议问题