How to grep the git diff?

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

    I think your approach to "grep" diff output is the best workaround.

    You may improve your awk script by using sed:

    colored="(^[\[[0-9;]*[a-zA-Z])"
    marker="^$colored+diff"
    pattern="^$colored+.*(\+|\-).*PATTERN"
    git diff --color | sed -rn -e "/$marker/! H; /$marker/ ba; $ ba; b; :a; x; /$pattern/ p"
    
    • colored: regex to match terminal colored lines
    • marker: marker to match division from differents diff hunks, lines starting with colored "diff"
    • pattern: pattern to search for, lines starting with colored "+" or "-" and containing "PATTERN"

    This will print full diff hunks, with added or removed PATTERN, also maintaining useful colored output.

    Note that ^[ in colored should be actual, literal ^[. You can type them in bash by pressing Ctrl + V, Ctrl + [

提交回复
热议问题